Sri*_*nth 3 sql-server csv parsing
我有一个具有特定列的表,其中有一个列包含逗号分隔值,如test,exam,result,other.
我将一个字符串,如result,sample,unknown,extras作为参数传递给存储过程.然后我想通过检查此字符串中的每个短语来获取相关记录.
例如:
表A
ID Name Words
1 samson test,exam,result,other
2 john sample,no query
3 smith tester,SE
Run Code Online (Sandbox Code Playgroud)
现在我想搜索结果,样本,未知,额外内容
然后结果应该是
ID Name Words
1 samson test,exam,result,other
2 john sample,no query
Run Code Online (Sandbox Code Playgroud)
因为在第一个记录结果匹配和第二个记录样本匹配.
你知道,这不是一个伟大的设计.最好将单词分成单独的表(id,word).
那说,这应该做的伎俩:
set nocount on
declare @words varchar(max) = 'result,sample,unknown,extras'
declare @split table (word varchar(64))
declare @word varchar(64), @start int, @end int, @stop int
-- string split in 8 lines
select @words += ',', @start = 1, @stop = len(@words)+1
while @start < @stop begin
select
@end = charindex(',',@words,@start)
, @word = rtrim(ltrim(substring(@words,@start,@end-@start)))
, @start = @end+1
insert @split values (@word)
end
select * from TableA a
where exists (
select * from @split w
where charindex(','+w.word+',',','+a.words+',') > 0
)
Run Code Online (Sandbox Code Playgroud)
我可以在DBA地狱中为你提供这个!
编辑:替换STUFF w/SUBSTRING切片,在长列表上快一个数量级.
| 归档时间: |
|
| 查看次数: |
6183 次 |
| 最近记录: |