问题
I am collecting data from a t-sql stored procedure to import into c# program. I would like to narrow down the data first. I have data that has three field that describes the three values that follows them. I need to find only the fields that have one of a dozen keywords in the description.
I was using something that UNION all the fields with values, then
...
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%'
...
Now I am trying to do something like this:
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)
...
(This is one of a number of similar UNION pieces. Which is why I would like to use a list of words, to shorten the code, and contain the words in one place in case of future changes.)
OR something Like:
SELECT *
FROM [DB1].dbo.Table_info
WHERE Account = 'TEXT1234'
AND AccountValue CONTAINS (SELECT * FROM @wordList)
...
Expected output:
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
Please let me know if you need more code to analyze this... (I am failing at keeping this brief already.)
回答1:
Use EXISTS:
SELECT *
FROM [DB1].dbo.Table_info tbl
WHERE tbl.Account = 'TEXT1234'
AND EXISTS
(
SELECT 0
FROM @wordList wl
WHERE tbl.AccountValue LIKE wl.Word
)
来源:https://stackoverflow.com/questions/58714762/find-rows-where-the-value-contains-a-word-from-a-list-of-varchar50