条件where子句T-SQL

Tom*_*Tom 3 t-sql sql-server-2008

我有一个返回数据的存储过程.

我需要根据传入的参数更改where子句.

例如,参数是:

@Region NVARHCAR(15)
@CountryCode NVARCHAR(2)
@ProductA BIT
@ProductB BIT
@ProductC BIT
Run Code Online (Sandbox Code Playgroud)

如果传入@Region,则应按区域选择where,如果传入@CountryCode则应按国家/地区代码选择where.

对于产品,如果其中任何一个设置为true,那么应该在哪里选择该项目的数据.

因此,如果传入@Region并且@ProductA和@ProductC设置为true,则该语句可能如下所示:

SELECT *
FROM table
WHERE Region = @Region AND
(Product = 'ProductA' OR Product = 'ProductC')
Run Code Online (Sandbox Code Playgroud)

或者,条件产品可以是IN语句.

如果传入了@CountryCode,它将如下所示:

SELECT *
FROM table
WHERE CountryCode = @CountryCode AND
(Product = 'ProductA' OR Product = 'ProductC')
Run Code Online (Sandbox Code Playgroud)

甚至可能传入@CountryCode和@Region.

有没有办法用T-SQL做这个,而不是从应用程序生成动态SQL?

谢谢

Jus*_*son 6

您不需要构建动态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'))
Run Code Online (Sandbox Code Playgroud)

如果您的SQL是这样构建的,那么当您传入@Region参数的值时,您只会在Region列上进行过滤.CountryCode也是如此.