[英]SQL for return all the id which does not exist in db and passing in sql
I need some help writing an SQL statement for the below requirement. 我需要一些帮助来编写满足以下要求的SQL语句。
I have list of employee_id which I need to check whether they are exist in the DB or not from the java
layer I want to use one query for this. 我有employee_id列表,我需要从
java
层检查它们是否存在于数据库中,我想对此使用一个查询。
Sample query: 查询样例:
SELECT *
FROM employee
WHERE employee_id IN (1001,1002,1002,10000004).
In this query 10000004
does not exist in DB. 在此查询中,数据库中不存在
10000004
。
One approach in my mind is to use the below query: 我想到的一种方法是使用以下查询:
SELECT Count(employee_id)
FROM employee
WHERE employee_id IN (1001,1002,1002,10000004).
Then check the list size and the result from the query in java layer. 然后在Java层中检查列表大小和查询结果。 But I don't want this because I need all those
employee_id
which does not exist in DB. 但是我不希望这样,因为我需要所有DB中不存在的所有
employee_id
。
declare @employeeids varchar(1000) --to store ids as comma seperated string
declare @tmpEmployee table (employee_id varchar(50)) --temp employee table to store ids from string
declare @pointer int
select @employeeids = '1001,1002,1002,10000004' --list of ids to check against database
while (charindex(',', @employeeids, 0) > 0)
begin
set @pointer = charindex(',', @employeeids, 0)
insert into @tmpEmployee (employee_id)
--remove white spaces if exists
select ltrim(rtrim(substring(@employeeids, 0, @pointer)))
set @employeeids = stuff(@employeeids, 1, @pointer, '')
end
insert into @tmpEmployee (employee_id)
select ltrim(rtrim(@employeeids))
select r.employee_id -- required ids which does not exists in database
,e.employee_id
from @tmpEmployee r
left join employee e on r.employee_id=e.employee_id
where e.employee_id is null
Exist a very bad way to do that is this: 存在一个非常糟糕的方法是这样的:
SELECT * FROM (SELECT 5930 id UNION SELECT 8109 id
UNION SELECT 8110 id UNION SELECT 8115 id UNION SELECT 8112 id
UNION SELECT 8113 id UNION SELECT -1 id) b
WHERE b.id NOT IN (SELECT f.id FROM employee f)
I recommed you do that in other way. 我建议您以其他方式这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.