Not in In SQL statement?

时光毁灭记忆、已成空白 提交于 2019-12-05 05:34:56

You're probably looking for EXCEPT:

SELECT Value 
FROM @Excel 
EXCEPT
SELECT Value 
FROM @Table;

Edit:

Except will

  • treat NULL differently(NULL values are matching)
  • apply DISTINCT

unlike NOT IN

Here's your sample data:

declare @Excel Table(Value int);
INSERT INTO @Excel VALUES(1);
INSERT INTO @Excel VALUES(2);
INSERT INTO @Excel VALUES(3);
INSERT INTO @Excel VALUES(4);
INSERT INTO @Excel VALUES(5);
INSERT INTO @Excel VALUES(6);
INSERT INTO @Excel VALUES(7);
INSERT INTO @Excel VALUES(8);
INSERT INTO @Excel VALUES(9);
INSERT INTO @Excel VALUES(10);

declare @Table Table(Value int);
INSERT INTO @Table VALUES(1);
INSERT INTO @Table VALUES(2);
INSERT INTO @Table VALUES(3);
INSERT INTO @Table VALUES(4);
INSERT INTO @Table VALUES(6);
INSERT INTO @Table VALUES(8);
INSERT INTO @Table VALUES(9);
INSERT INTO @Table VALUES(11);
INSERT INTO @Table VALUES(12);
INSERT INTO @Table VALUES(14);
INSERT INTO @Table VALUES(15);

Try this:

SELECT    tableExcel.ID
FROM      tableExcel
WHERE     tableExcel.ID NOT IN(SELECT anotherTable.ID FROM anotherTable)

Here's an SQL Fiddle to try this: sqlfiddle.com/#!6/31af5/14

Import your excel file into SQL Server using the Import Data Wizard found in SQL Server Management Studio.

Then you can write the following query to find any IDs which are in the file but not in the table:

SELECT id     
FROM imported_table
WHERE id NOT IN (SELECT id FROM db_table)

You should move excel data to a table in SQL Server, and then do the query in SQL Server.

  select distinct id from Excel where id not in (select your ids from Sqltable)

(Obviously select your ids from Sqltable is a select which returns the Ids existing on SQL Server).

You may think that moving data to SQL Server is hard to do, but, on the contrary, it's very easy:

1) create a table

  CREATE TABLE ExcelIds (Id int)

2) add a new column in excel with the following formula:

  ="insert into ExcelIds values(" & XX & ")"

where XX is the reference to the cell in the column with excel Ids.

3) copy the "inserts" from Excel into SSMS or whatever tool you're usin in SQL Server, and execute them.

Now you have 2 tables in SQL Server, so that querying it is absolutely easy.

When you're over, just drop the table

DROP TABLE ExcelIds

NOTE: I didn't create a key on SQL Server table because I suppose that the Ids can be repeated. Neither is justified to create a more complex SQL Query to avoid duplicates in ExcelIds for this ad hoc solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!