多列和 IN 运算符

Multiple columns and the IN operator

有一个table:

CREATE TABLE dbo.TestTable
    ( id INT IDENTITY(1, 1) NOT NULL
    , data1 VARCHAR(255) NULL
    , data2 VARCHAR(255) NULL
    , data3 VARCHAR(255) NULL
    )

...和一些示例数据:

INSERT  INTO dbo.TestTable
VALUES    ( 'some data'  , 'some other data'  , 'and another')
        , ( 'some data 2', 'some other data 2', 'and another 2')
        , ( 'some data 3', 'some other data 3', 'and another 3')
        , ( 'some data 4', 'some other data 4', 'and another 4')
        , ( 'some data 5', 'some other data 5', 'and another 5')
        , ( 'some data 6', 'some other data 6', 'and another 6')

... 最后是一个简单的 SELECT 查询:

SELECT *
FROM dbo.TestTable tt 
WHERE  tt.data1 IN ('x', 'y', 'z')
    OR tt.data2 IN ('x', 'y', 'z')
    OR tt.data3 IN ('x', 'y', 'z')

注意:在我的实际场景中,IN 运算符中的值数量和 dataXX 列的数量都要大得多。

如您所见,所查找的值列表('x'、'y'、'z')重复了多次。我正在寻找构建此查询的 "smarter" 方法,纯粹是为了避免多次复制 "OR tt.dataXX in (...)" 行。

有什么方法可以在上面的 SELECT 查询中仅使用一次 ('x', 'y', 'z') 值列表并让所有 tt.dataXX 列已涵盖?

如果有,那是什么?

我不能在这里测试它,但是你应该可以使用 table value constructor.

来做这样的事情
SELECT *
FROM dbo.TestTable tt
WHERE EXIST (
    SELECT 1
    FROM (VALUES ('x'), ('y'), ('z')) AS b(Name)
    WHERE b.Name IN (tt.data1, tt.data2, tt.data3)
)