我有一个返回数据的存储过程。
我需要根据传入的参数更改 where 子句。
例如参数为:
@Region NVARHCAR(15)
@CountryCode NVARCHAR(2)
@ProductA BIT
@ProductB BIT
@ProductC BIT
如果传入@Region,则where应按地区选择,如果传入@CountryCode,则where应按国家代码选择。
对于产品,如果其中任何一个设置为 true,则 where 应选择该项目的数据。
因此,如果传入 @Region 并将 @ProductA 和 @ProductC 设置为 true,则语句可能如下所示:
SELECT *
FROM table
WHERE Region = @Region AND
(Product = 'ProductA' OR Product = 'ProductC')
或者,产品条件可以是 IN 语句。
如果传入@CountryCode,它将如下所示:
SELECT *
FROM table
WHERE CountryCode = @CountryCode AND
(Product = 'ProductA' OR Product = 'ProductC')
甚至可以传入 @CountryCode 和 @Region。
有什么方法可以使用 T-SQL 而不是从应用程序生成的动态 SQL 来执行此操作?
谢谢
最佳答案
您不需要构建动态 SQL 语句,只需检查参数的值。以下是我通常如何构建 SQL 子句来实现此目的:
WHERE ((@Region IS NULL) OR (Region = @Region))
AND ((@CountryCode IS NULL) OR (CountryCode = @CountryCode))
AND ((@ProductA = 0) OR (Product = 'ProductA'))
AND ((@ProductB = 0) OR (Product = 'ProductB'))
AND ((@ProductC = 0) OR (Product = 'ProductC'))
如果您的 SQL 是这样构建的,那么当您传入 @Region 参数的值时,您只会过滤 Region 列。 CountryCode 也是如此。
关于tsql - 条件 where 子句 T-SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531539/