2

I have a Database of 10 Columns,
let it be like A,B,C,D,E,F,G,H,I,J

Now if i want to extract data with a mix of 4 options
i.e say B,C,H,J (B is my primary key)
and none of them are mandatory to give data in the option.
say
Case 1 : B,C,H is given as parameters and J is given null

for all such cases I have to make a nested if Else statement ?

Because it will go for 4! (factorial)= 24 cases

Is there any easy option for this???

4

2 回答 2

1

是的。一种选择(但有警告):

   WHERE
       (@paramA IS NULL OR Some Condition involving @paramA) AND
       (@paramB IS NULL OR Some Condition involving @paramB) AND
        ....
       (@paramH IS NULL OR Some Condition involving @paramH)

需要注意的是,这可能会使您的存储过程对不适合特定参数集的参数嗅探和缓存查询计划敏感。

另一种选择是构建动态 TSQL。

正如@ Damien_The_Unbeliever 所指出的:Erland Sommarskog 的SQL 中的动态搜索条件是一个很好的起点。

于 2013-07-01T06:19:07.057 回答
0

这是一个关于如何使用动态 SQL 执行此操作的示例,但我也强烈建议您阅读 Mitch 和 Demien 共享的文章。

CREATE PROCEDURE dbo.SearchProc
(
@param1 datetime,
@param2 int,
@param3 nvarchar
)
AS 
BEGIN

DECLARE @sql nvarchar(4000)
DECLARE @parameters nvarchar(300)

SET @sql = 'SELECT * FROM TableName WHERE (1=1) '

if @param1 is not null
SET @sql = @sql + ' AND TableName.Column1 = @param1'

if @param2 is not null
SET @sql = @sql + ' AND TableName.Column2 = @param2'

if @param3 is not null
SET @sql = @sql + ' AND TableName.Column3 = @param3'

SET @parameters = '@param1 datetime, @param2 int, @param3 nvarchar'

EXEC sp_executesql @sql, @parameters, @param1, @param2, @param3

END
于 2013-07-01T10:59:24.843 回答