首页 > 解决方案 > 从 varchar(50) 列表中查找值包含单词的行

问题描述

我正在从 t-sql 存储过程收集数据以导入 c# 程序。我想先缩小数据范围。我有包含三个字段的数据,这些字段描述了它们后面的三个值。我只需要找到描述中包含十几个关键字之一的字段。

我正在使用 UNION 所有具有值的字段,然后

...
AND (
        TEXT1234.AccountValue LIKE '%word1%'
     OR TEXT2345.AccountValue LIKE '%word1%'
     OR TEXT3456.AccountValue LIKE '%word1%'

     OR TEXT1234.AccountValue LIKE '%word2%'
     OR TEXT2345.AccountValue LIKE '%word2%'
     OR TEXT3456.AccountValue LIKE '%word2%'

     OR TEXT1234.AccountValue LIKE '%word3%'
     OR TEXT2345.AccountValue LIKE '%word3%'
     OR TEXT3456.AccountValue LIKE '%word3%'
...

现在我正在尝试做这样的事情:

declare @wordList table (Word varchar(50))
insert into @wordList values ('%word1%'),('%word2%'),('%word3%')...

...
SELECT *
FROM [DB1].dbo.Table_info
WHERE Account = 'TEXT1234'
AND AccountValue LIKE (SELECT * FROM @wordList)
...

(这是许多类似的 UNION 作品之一。这就是为什么我想使用一个单词列表来缩短代码,并将单词包含在一个地方以防将来发生变化。)

或类似的东西:

SELECT *
FROM [DB1].dbo.Table_info
WHERE Account = 'TEXT1234'
AND AccountValue CONTAINS (SELECT * FROM @wordList)
...

预期输出:

TEXT1234_Account   TEXT1234_AccountValue       Acct1234   Acct1234_Value
TEXT1234           word3 something something   ACCT1234   48

TEXT3456_Account   TEXT3456_AccountValue        Acct3456   Acct3456_Value
TEXT3456           Something word1 something    ACCT3456   48

如果您需要更多代码来分析这个,请告诉我......(我已经无法保持这个简短了。)

标签: sql-servertsql

解决方案


使用存在:

SELECT *
FROM [DB1].dbo.Table_info tbl
WHERE tbl.Account = 'TEXT1234'
AND EXISTS
(
    SELECT 0
    FROM @wordList wl
    WHERE tbl.AccountValue LIKE wl.Word
)

推荐阅读