我有一个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
我得到所有记录
请根据我的案例中的类型建议如何过滤记录
答案 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, ''))