任何人都可以建议对具有多个值的单个参数执行select的最佳方法。例如:
表:员工
Employee_id Resigned City
1 False JP
2 True AJ
5 False AJ
输入参数类似于1,2,3,4,5,6,7(Employee_id)
SELECT e.employee_id, e.resigned FROM Employee e
where e.employee_id IN (1,2,3,4,5,6,7)
这里的问题是从上面的查询返回的是: 1对 2对 5错误
但是我正在寻找这样的东西: 1对 2对 3错 4错 5错 6错 7错误
当没有行出现时返回false。
答案 0 :(得分:2)
您可以使用left join
:
WITH eids as (
SELECT 1 as employee_id FROM dual union all
SELECT 2 FROM dual union all
SELECT 3 FROM dual union all
SELECT 4 FROM dual union all
SELECT 5 FROM dual union all
SELECT 6 FROM dual union all
SELECT 7 FROM dual
)
SELECT eids.employee_id, COALESCE(e.resigned, 'False')
FROM eids LEFT JOIN
Employee e
ON eids.employee_id = e.employee_id;
答案 1 :(得分:-1)
您需要创建UDF以将逗号分隔的参数转换为表格。这将是一次性脚本,您可以使用此功能加入。
CREATE FUNCTION [dbo].[myFunc] (@inputStr VARCHAR(MAX))
RETURNS @TempTab TABLE
(EmpID int not null)
AS
BEGIN
;-- Ensure input ends with comma
SET @inputStr = REPLACE(@inputStr + ',', ',,', ',')
DECLARE @SP INT
DECLARE @VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', @inputStr ) <> 0
BEGIN
SELECT @SP = PATINDEX('%,%',@inputStr)
SELECT @VALUE = LEFT(@inputStr , @SP - 1)
SELECT @inputStr = STUFF(@inputStr, 1, @SP, '')
INSERT INTO @TempTab(EmpID) VALUES (@VALUE)
END
RETURN
END
然后有一个简单的查询来获得结果 -
Declare @Parameter varchar(25)
set @Parameter = '10,11,12,13,14,15'
select t.id, ISNULL(E.resigned ,'False')from
(select * from myFunc(@Parameter))t
left outer join Employee E
on t.empid = E.Employee_ID