文本搜索字符串

时间:2015-01-14 16:23:17

标签: c# sql sql-server

我有以下字符串。

  汽车,公共汽车,自行车,房子

我想将它们分成单独的字符串并在where子句中使用它们,所以它想要这样:

SELECT [text]
FROM [table]
WHERE
text LIKE 'bus'
or text LIKE 'car'
or text LIKE 'bike'
or text LIKE 'house'

您将如何浏览原始字符串并将其拆分为单个子字符串。原始文本字符串作为变量从GUI传递。到目前为止,我们有这个

REPLACE(LEFT('%BIKE, BUS, HOUSE%',CHARINDEX(',','%BIKE, BUS, HOUSE%')),',','%'),
REPLACE(SUBSTRING('%BIKE, BUS, HOUSE%',CHARINDEX(',','%LADDER, BA%'),LEN('%BIKE, BUS, HOUSE%')),',','%'),

但是这只会在第一个逗号之前返回一个子字符串并保留所有内容。例如' bike'和'汽车,公共汽车,房子'。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

将LINQ与PredicateBuilder(http://www.albahari.com/nutshell/predicatebuilder.aspx

一起使用

(示例 - 我有一个方便的ZipCodes表)

var codes = "77,88,99".Split(',');

var predicate = PredicateBuilder.False<ZipCodes>();
foreach(var c in codes)
    predicate = predicate.Or(z=>z.ZipCode.Contains(c));

var answer = this.ZipCodes.Where(predicate).ToList();

答案 1 :(得分:1)

您可以使用XML功能将字符串转换为数组,然后只使用通配符JOIN

DECLARE @string VARCHAR(100) = 'car, bus, bike, house'
;WITH cte AS (SELECT RTRIM(LTRIM(Split.a.value('.', 'VARCHAR(100)'))) AS Txt    
              FROM  (SELECT CAST ('<M>' + REPLACE(@string, ',', '</M><M>') + '</M>' AS XML) AS DATA
              ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a))
SELECT DISTINCT [text]
FROM [table] a
JOIN cte b
  ON a.[text] LIKE '%'+b.Txt+'%'

理想情况下,您将数组传递给表变量,只需在底部运行JOIN