0

我有一个没有返回正确结果的查询:

 SELECT t.GroupName AS GroupName, t.ApplicationName AS ApplicationName, t.UserName
        FROM UserApplication t
        WHERE (@ApplicationName IS NULL OR @ApplicationName = '' OR t.ApplicationName = @ApplicationName) AND
              (@UserName IS NULL OR @UserName = '' OR t.UserName= @UserName );

表结构:

CREATE TABLE userapplication
            (`ID` INT,
             `ApplicationName` VARCHAR(100),
             `GroupName` VARCHAR(100),
             `UserName` VARCHAR(100))

当我没有将任何值传递给参数时,它会显示表中的所有行,而如果将任何值传递给参数 @ApplicationName 或 @UserName 它会给我相同的结果。请帮忙

4

1 回答 1

1

If you correctly set values of user variables your query will work just fine

SET @ApplicationName = 'App 1';
SET @UserName = '';

SELECT t.GroupName, 
       t.ApplicationName, 
       t.UserName
  FROM UserApplication t
 WHERE (COALESCE(@ApplicationName, '') = '' 
     OR t.ApplicationName = @ApplicationName) 
   AND (COALESCE(@UserName, '') = '' 
     OR t.UserName= @UserName);

It's a little bit more succinct version of your query

Here is SQLFiddle demo

于 2013-06-12T06:08:04.557 回答