是否可以在存储过程中的where子句中使用参数?

时间:2016-10-26 10:57:04

标签: sql-server tsql stored-procedures

我正在使用SQL Server 2012。

我有一个名为myDataTable的表:

| Id | ExternalId | Subject | CMT           |    
| 1  |   3379     | damage5 | some comment7 |
| 2  |   3380     | damage3 | some comment3 | 
| 3  |   3382     | damage4 | some comment5 |
| 4  |   3381     | damage1 | some comment4 |

ExternalId列的类型为Int

CMT列的类型为nvarchar(max)

我传递给字符串类型的存储过程参数@filterParam

在存储过程中,我需要检查@filterParam是否包含至少一个我使用@filterParam的字母来过滤选择主题列,如下所示:

ALTER PROCEDURE [dbo].[SPGeneralReport]
            @filterParam nvarchar(max),
            @CMTParam nvarchar(max)
AS
BEGIN

SET NOCOUNT ON;
SELECT      *                
FROM        myDataTable
WHERE       Subject = @filterParam AND CMT = @CMTParam
END

在存储过程中,我需要检查@filterParam是否只包含我需要将其转换为整数的数字,并在WHERE子句中使用它来过滤使用ExternalId列的选择:

ALTER PROCEDURE [dbo].[SPGeneralReport]
            @filterParam nvarchar(max)
AS
BEGIN

SET NOCOUNT ON;
SELECT      *                
FROM        myDataTable
WHERE       ExternalId = @filterParam AND CMT = @CMTParam
END

如果@filterParam为NULL,我不想在我的过滤器中使用它:

ALTER PROCEDURE [dbo].[SPGeneralReport]
            @filterParam nvarchar(max)
AS
BEGIN

SET NOCOUNT ON;
SELECT      *                
FROM        myDataTable
WHERE       CMT = @CMTParam 
END

我不想创建多个存储过程,我想用过滤器的可选参数创建单个过程。

知道如何实现它?

2 个答案:

答案 0 :(得分:1)

使用OR条件

WHERE (ExternalId = @filterParam OR @filterParam IS NULL)
  AND CMT = @CMTParam

@filterParamNULL时,将不会应用第一个条件

答案 1 :(得分:1)

由于你在这种情况下有3例,我会做这样的事情。首先过滤掉common子句,然后在另一个过滤器上使用条件语句(注意我必须启用Ole Automation Procedures)。

Create Table #Temp
(
    Id INT,
    ExternalId Int,
    [Subject] NVarChar(128),
    Comment NVarChar(128)
)

Insert Into #Temp
Values

( 1  ,   3379     ,'damage5' ,'some comment7' ),
( 2  ,   3380     ,'damage3' ,'some comment4' ),
( 3  ,   3382     ,'damage4' ,'some comment5' ),
( 4  ,   3381     ,'damage1' ,'some comment4' )

Declare @filterParam nvarchar(max) = '3380', 
        @CMTParam nvarchar(max) = 'some comment4'

Select * Into #OtherTemp
From #Temp
Where Comment = @CMTParam

IF(@filterParam IS NULL)
Begin
    Select * 
    From #OtherTemp
End
Else If (dbo.fn_regex('^\d*$',@filterParam) <> 0)
Begin
    Select * 
    From #OtherTemp
    where ExternalId = Cast(@filterParam AS Int)
End
Else
Begin
    Select * 
    From #OtherTemp
    where Subject= @filterParam
End

Drop Table #Temp
Drop Table #OtherTemp

另一种方法是创建2个变量并在那里执行解析并在where子句中使用结果

Declare @filterSubject NVarChar(128), @filterId Int

If (dbo.fn_regex('^\d*$',@filterParam) <> 0)
Begin
    SET @filterId = Cast(@filterParam AS Int)
End
Else If (@filterParam IS NOT NULL)
Begin
    SET @filterSubject =  @filterParam
End 


Select * 
From #Temp
Where (@filterId IS NULL OR ExternalId = @filterId) 
        AND (@filterSubject IS NULL OR Subject =@filterSubject)
        AND Comment = @CMTParam