字符串文本搜索
String of text search
我有以下字符串。
car, bus, bike, house
我想将它们拆分成单独的字符串并在 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' 和 'car, bus, house'.
有什么想法吗?
将 LINQ 与 PredicateBuilder 结合使用(http://www.albahari.com/nutshell/predicatebuilder.aspx)
(示例 -- 我手边有 table 邮政编码)
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();
您可以使用 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+'%'
理想情况下,您会将数组传递给 table 变量,只需 运行 底部的 JOIN
。
我有以下字符串。
car, bus, bike, house
我想将它们拆分成单独的字符串并在 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' 和 'car, bus, house'.
有什么想法吗?
将 LINQ 与 PredicateBuilder 结合使用(http://www.albahari.com/nutshell/predicatebuilder.aspx)
(示例 -- 我手边有 table 邮政编码)
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();
您可以使用 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+'%'
理想情况下,您会将数组传递给 table 变量,只需 运行 底部的 JOIN
。