我假设您的列表是一个字符串/varchar,那么您首先需要一个拆分函数来获取所有部分:
1.) 然后可以使用 anINNER JOIN
查找表中的所有内容:
SELECT CityId,CityName
FROM Cities c
INNER JOIN dbo.Split('ABC,DEF,MNO,PQR,STU',',')x
ON c.CityName = x.Item;
2.)并 NOT EXISTS
查找列表中但不在表中的所有内容:
SELECT x.Item As CityName
FROM dbo.Split('ABC,DEF,MNO,PQR,STU',',')x
WHERE NOT EXISTS
(
SELECT 1
FROM Cities c
WHERE c.CityName = x.Item
)
演示
结果:
1)
CITYID CITYNAME
1 ABC
2 DEF
5 MNO
2)
CITYNAME
PQR
STU
这是我的拆分功能:
CREATE FUNCTION [dbo].[Split]
(
@ItemList NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @IDTable TABLE (Item VARCHAR(50))
AS
BEGIN
DECLARE @tempItemList NVARCHAR(MAX)
SET @tempItemList = @ItemList
DECLARE @i INT
DECLARE @Item NVARCHAR(4000)
SET @tempItemList = REPLACE (@tempItemList, ' ', '')
SET @i = CHARINDEX(@delimiter, @tempItemList)
WHILE (LEN(@tempItemList) > 0)
BEGIN
IF @i = 0
SET @Item = @tempItemList
ELSE
SET @Item = LEFT(@tempItemList, @i - 1)
INSERT INTO @IDTable(Item) VALUES(@Item)
IF @i = 0
SET @tempItemList = ''
ELSE
SET @tempItemList = RIGHT(@tempItemList, LEN(@tempItemList) - @i)
SET @i = CHARINDEX(@delimiter, @tempItemList)
END
RETURN
END