TSQL中的条件基于输入参数

时间:2013-11-04 09:51:52

标签: sql sql-server tsql

我有一个sql server表,其中一个名为[type]的int列可以为空。我有以下存储过程,它将类型作为输入:

    @Jobtype VARCHAR(50) = '',  
    @Language INT
AS
BEGIN
    SELECT [TabId]      
      ,CASE
            WHEN @Language = 2 THEN [TabNameTextLang2]
            ELSE [TabNameTextLang1]
        END AS TabName
      ,CASE
            WHEN @Language = 2 THEN [PageTitleLang2]
            ELSE [PageTitleLang1]
        END AS PageTitle
      ,[TabLink]
      ,[Type]
      ,[Priority]
      ,[DutyStationId]
      ,[DateCreated]
      ,[DateModified]
      ,[Deleted]
    FROM dbo.hr_Tabs
    WHERE Deleted = 0 AND 
    ((@Jobtype = '' and [Type] is null) or  ([Type] = CASt(@Jobtype as int )))

END

此表有一行,其中type为null。我希望当我将@jobtype传递为''时,只选择该行,否则按类型显示行。但是,当我尝试传递上面的存储过程参数,如

exec myproce '', 1

我得到所有记录

请根据我的案例中的类型建议如何过滤记录

2 个答案:

答案 0 :(得分:2)

使用:

((@Jobtype = '' and [Type] is null) or
 (@Jobtype <> '' and [Type] = CAST(@Jobtype as int )))

(我通常建议使用NULL而不是空字符串作为您的特殊标记值)

答案 1 :(得分:-1)

替代

FROM dbo.hr_Tabs
CROSS APPLY (select [Type] as dummy intersect select nullif(@Jobtype, '')) x
WHERE Deleted = 0

为了与先生完全匹配。史密斯的答案(逻辑是一样的):

FROM dbo.hr_Tabs
WHERE Deleted = 0 and exists 
(select [Type] as dummy intersect select nullif(@Jobtype, ''))