我有一个数据库表,其中包含存储逗号分隔字符串值的列。 比如说
Row CSVColumn
1. value1, value2
2. value1, value3
3. value2, value4
我的搜索参数再次以逗号分隔,例如value2,value4
现在我想返回与搜索参数匹配的所有行。在此示例中应返回第1行和第3行。
有人可以为此编写MS SQL查询吗?
答案 0 :(得分:1)
这个例子怎么样。我将字符串拆分为搜索字符串和CSVColumn的行。
之后,我只是INNER加入他们。
我使用xml进行拆分,但你也可以为此创建函数。
DECLARE @CsvTable TABLE (Rowid INT, CsvColumn VARCHAR(MAX))
INSERT INTO @CsvTable SELECT '1', 'value1'
INSERT INTO @CsvTable SELECT '2', 'value1, value3'
INSERT INTO @CsvTable SELECT '3', 'value2, value4'
DECLARE @SearchText VARCHAR(20) = 'value2, value3'
;WITH SearchTable AS (
SELECT LTRIM(O.splitdata) AS Searchdata
FROM (
SELECT CAST('<X>'+replace(@SearchText,',','</X><X>')+'</X>' AS XML) AS XmlData
) AS xT
CROSS APPLY
(
SELECT xdata.D.value('.', 'VARCHAR(50)') AS splitdata
FROM xT.XmlData.nodes('X') as xdata(D)
) O
), SplitTable AS (
SELECT xT.Rowid,
LTRIM(O.splitdata) AS splitdata
FROM (
SELECT T.Rowid, CAST('<X>'+replace(T.CsvColumn,',','</X><X>')+'</X>' AS XML) AS XmlData
FROM @CsvTable AS T
) AS xT
CROSS APPLY
(
SELECT xdata.D.value('.', 'VARCHAR(50)') AS splitdata
FROM xT.XmlData.nodes('X') as xdata(D)
) O
)
SELECT DISTINCT CT.*
FROM @CsvTable AS CT
INNER JOIN SplitTable AS SplitT
ON SplitT.RowID = CT.RowID
INNER JOIN SearchTable AS SrchT
ON SrchT.Searchdata = SplitT.splitdata