我需要重写以下两个查询以避免OR @MyParam IS NULL检查(使用CASE is not working properly中提到的CASE语句)
是否可以以该格式重写以下查询?
注意:How to pass string parameter with `IN` operator in stored procedure SQL Server 2008
中提供了fn_Split功能DECLARE @MyParam VARCHAR(MAX)
SET @MyParam = '2,3'
DECLARE @MyTable TABLE (EmpID INT)
INSERT INTO @MyTable VALUES (1)
INSERT INTO @MyTable VALUES (2)
INSERT INTO @MyTable VALUES (3)
INSERT INTO @MyTable VALUES (4)
--Query 1
SELECT *
FROM @MyTable M
WHERE (
M.EmpID IN (SELECT CONVERT(int,Value) FROM fn_Split(@MyParam, ','))
OR @MyParam IS NULL
)
--Query 2
SELECT *
FROM @MyTable M
WHERE (EXISTS (
SELECT CONVERT(int,Value)
FROM fn_Split(@MyParam, ',')
WHERE CONVERT(int,Value) = M.EmpID
)
OR @MyParam IS NULL
)
答案 0 :(得分:1)
使用左连接
SELECT m.*
FROM @MyTable M
left join (SELECT CONVERT(int,Value) v FROM fn_Split(@MyParam, ',')) t
on m.EmpID = t.v
where v is not null or @MyParam is null
理想情况下,您不会将包含多个值的字符串作为参数传递 - 如果这是一个存储过程,请使用table valued parameter