简体   繁体   English

文字搜寻字串

[英]String of text search

I have the following string. 我有以下字符串。

car, bus, bike, house 汽车,公共汽车,自行车,房屋

I would like to split these into individual strings and use them in a where clause so it would like this: 我想将它们拆分成单独的字符串,并在where子句中使用它们,因此它是这样的:

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

How would you go through the original string and split them out into individual substrings. 您将如何遍历原始字符串并将其拆分为单独的子字符串。 The original text string is being passed as variable from a GUI. 原始文本字符串将从GUI作为变量传递。 So far we have this 到目前为止,我们有这个

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

But that only brings back a substring before the first comma and keeps everything after. 但这只会在第一个逗号之前返回一个子字符串,并在之后保留所有内容。 eg 'bike' and 'car, bus, house'. 例如“自行车”和“汽车,公共汽车,房屋”。

Any ideas? 有任何想法吗?

Use LINQ with the PredicateBuilder ( http://www.albahari.com/nutshell/predicatebuilder.aspx ) 将LINQ与PredicateBuilder一起使用( http://www.albahari.com/nutshell/predicatebuilder.aspx

(Sample -- I had a table of ZipCodes handy) (示例-我有一个方便的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();

You can use XML functionality to turn your string into an array, then simply JOIN with wildcards: 您可以使用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+'%'

Ideally you'd pass your array into a table variable and just have to run the JOIN at the bottom. 理想情况下,您要将数组传递到表变量中,而只需要在底部运行JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM