1

使用 MS SQL 服务器 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 设置为一种语言,即英语,则查询返回数据。

但是,如果所有参数都设置为默认值,则不会返回任何内容,但我需要返回所有记录,我感觉逻辑缺少一些非常简单的东西,但我的眼睛看不出原因。

有什么线索吗?

4

3 回答 3

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 ))
于 2013-07-03T10:17:15.010 回答
0

在 where 子句中需要一个布尔条件:

WHERE ((@Country = 'DEFAULT') OR @Country!= 'DEFAULT' AND @Country != '' AND([Language] = @Country ))
AND

如果参数 country 不是default,它将应用该条件。否则,如果参数是默认值,则将跳过第二个条件。

于 2013-07-03T10:18:28.447 回答
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 ))
于 2013-07-03T10:21:52.647 回答