使用MS SQL server 2008。
我的查询如下:
SELECT * FROM #PreModuleAllData WITH(NOLOCK)
WHERE (@Country != 'DEFAULT' AND @Country != '' AND([Language] = @Country ))
OR (@UserType != 'DEFAULT' AND @UserType != '' AND([UserType] = @UserType ))
OR (@Group != 'DEFAULT' AND @Group != '' AND([Company] = @Group ))
OR (@CodeUsage != 'DEFAULT' AND @CodeUsage != '' AND([User Code]= @CodeUsage ))
如果任何参数设置为''或默认,则计划返回所有数据。 如果使用了参数,它应该根据特定的where子句返回。
例如,如果参数@country设置为一种语言,即英语,则查询返回数据。
但如果所有参数都设置为默认值,则不返回任何内容,但我需要返回所有记录,我感觉逻辑缺失的东西非常简单,但我的眼睛看不清楚原因。
任何线索?
答案 0 :(得分:4)
试试这个:
SELECT * FROM #PreModuleAllData WITH(NOLOCK)
WHERE (@Country = 'DEFAULT' OR @Country = '' OR ([Language] = @Country ))
AND (@UserType = 'DEFAULT' OR @UserType = '' OR ([UserType] = @UserType ))
AND (@Group = 'DEFAULT' OR @Group = '' OR ([Company] = @Group ))
AND (@CodeUsage = 'DEFAULT' OR @CodeUsage = '' OR ([User Code]= @CodeUsage ))
答案 1 :(得分:0)
你的where子句需要一个布尔条件:
WHERE ((@Country = 'DEFAULT') OR @Country!= 'DEFAULT' AND @Country != '' AND([Language] = @Country ))
AND
如果参数国家/地区不是default
,则会应用该条件。否则如果参数是默认值,那么将跳过第二个条件。
答案 2 :(得分:0)
你必须重写以下逻辑
SELECT * FROM #PreModuleAllData WITH(NOLOCK)
WHERE (@Country = 'DEFAULT' OR @Country = '' OR (@Country NOT IN ('DEFAULT','') AND [Language] = @Country ))
OR (@UserType = 'DEFAULT' OR @UserType = '' OR (@UserType NOT IN ('DEFAULT','') AND [UserType] = @UserType ))
OR (@Group = 'DEFAULT' OR @Group = '' OR (@Group NOT IN ('DEFAULT','') AND [Company] = @Group ))
OR (@CodeUsage = 'DEFAULT' OR @CodeUsage = '' OR (@CodeUsage NOT IN ('DEFAULT','') AND [User Code]= @CodeUsage ))