tsql - 条件 where 子句 T-SQL

标签 tsql sql-server-2008

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

我需要根据传入的参数更改 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/

相关文章:

sql-server-2005 - tsql : best way to cast variables to string type?

sql - T-SQL : How to select one column or in alternative another one?

sql - 如何从约会集中返回所有空闲时间段

sql-server-2008 - 从sql server中的记录中选择上个月的第一天

sql-server-2008 - SQL Server 组合结果集

json - 使用 FOR JSON PATH 创建嵌套 JSON 数组

sql-server - SQL Server 引用计算列

sql - 检查一个或多个 id 是否在 json 字符串中

sql-server - SSRS BIDS 2008 R2 饼图数据标签重叠

sql-server-2008 - SSMA 或 SSIS,用于从 Oracle 10 迁移到 SQL Server 2008 R2