在不使用 union 的情况下显示 table 中不存在的 where 子句元素

Show elements of where clause that are not present in table without using union

select * from tblCustomer where CustomerName in ('A','B','C','Y','Z')

假设客户 A、B 和 C 存在于 tblCustomer 中。

所以,我想要在SQL中输出Y,Z。不使用 union 子句的客户名称不存在于 tblCustomer 中。

如果是 SQL 服务器,您可以使用 Table 2008 版中引入的值构造函数。

select n as CustomerName from (values('A'), ('B'), ('C'), ('Y'),('Z')) a(n)
left join tblCustomer c
 on a.n = c.customerName
 where c.customerName is null

查询return:

CustomerName
-------
    Y
    Z

编辑: 您始终可以使用 returns table-values.

的函数
CREATE FUNCTION [dbo].[ListToTable]( @ValueList varchar( 2000 ) )
 RETURNS @ValuesTable TABLE ( Value varchar(80) )
AS
BEGIN

DECLARE
    @ValueSeparator varchar(1),
    @ValueSeparatorIndex int

SET @ValueSeparator = ',';

SET @ValueList = LTRIM( @ValueList )

SET @ValueSeparatorIndex = CHARINDEX ( @ValueSeparator, @ValueList );

WHILE @ValueSeparatorIndex > 0 
BEGIN
    INSERT INTO @ValuesTable( Value ) VALUES(  SUBSTRING( @ValueList, 1, @ValueSeparatorIndex - 1 ) );

    SET @ValueList  = LTRIM( SUBSTRING( @ValueList , @ValueSeparatorIndex + 1, LEN(@ValueList ) - @ValueSeparatorIndex ) );

    SET @ValueSeparatorIndex = CHARINDEX ( @ValueSeparator, @ValueList );
END

IF LEN(@ValueList) > 0 
    INSERT INTO @ValuesTable( Value ) VALUES( @ValueList  );

RETURN
END

之后您可以通过以下方式使用它:

select A.Value as CustomerName from ListToTable('A,B,C,X,Y') A
left join tblCustomer c
 on a.Value = c.customerName
 where c.customerName is null