cust_id | cust_name | cust_address | cust_city | cust_state | cust_country | cust_contact | cust_email |
---|---|---|---|---|---|---|---|
1000000001 | Village Toys | 200 Maple Lane | Detroit | MI | USA | John Smith | sales@villagetoys.com |
1000000002 | Kids Place | 333 South Lake Drive | Columbus | OH | USA | Michelle Green | NULL |
1000000003 | Fun4All | 1 Sunny Place | Muncie | IN | USA | Jim Jones | jjones@fun4all.com |
1000000004 | Fun4All | 829 Riverside Drive | Phoenix | AZ | USA | Denise L. Stephens | dstephens@fun4all.com |
1000000005 | The Toy Store | 4545 53rd Street | Chicago | IL | USA | Kim Howard | NULL |
--過濾出列表中不存在于數(shù)據(jù)庫中的項 --返回結果為['1000000006','1000000007'] SELECT [Id] AS [cust_id] FROM ( VALUES('1000000004'),('1000000005'),('1000000006'),('1000000007') ) dt ([Id]) EXCEPT SELECT [cust_id] FROM [Customers] --過濾出列表中存在于數(shù)據(jù)庫中的項 --返回結果為['1000000004','1000000005'] SELECT [Id] AS [cust_id] FROM ( VALUES('1000000004'),('1000000005'),('1000000006'),('1000000007') ) dt ([Id]) INTERSECT SELECT [cust_id] FROM [Customers]
--對于SQLServer 2008以前的版本 SELECT [Id] AS [cust_id] FROM ( SELECT '1000000004' UNION ALL SELECT '1000000005' UNION ALL SELECT '1000000006' UNION ALL SELECT '1000000007' ) dt ([Id]) INTERSECT --EXCEPT SELECT [cust_id] FROM [Customers]
//使用C#動態(tài)生成SQL語句 var list = new Liststring>(){"1000000004","1000000005","1000000006","1000000007"}; string sqlQuery = string.Format($@" SELECT [Id] AS [cust_id] FROM ( VALUES('{string.Join("'),('", list)}') ) dt ([Id] INTERSECT --EXCEPT SELECT [cust_id] FROM [Customers]" );
更多參考
Set Operators - EXCEPT and INTERSECT
Set Operators - UNION
到此這篇關于SQL Server中的集合運算: UNION, EXCEPT和INTERSECT的文章就介紹到這了,更多相關SQL Server中的集合運算內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!