CREATE TABLE test
(
[message] NVARCHAR(100) NULL,
)
INSERT INTO test
values
('Location set to: Loc1, Order: 1, item: shirt-red.large, company: 01, store: 01'),
('Location set to: Loc1, Order: 1, item: shirt-red.medium, company: 01, store: 01'),
('Location set to: Loc2, Order: 220, item: shirt-blue.small, company: 01, store: 089'),
('Location set to: Loc2, Order: 220, item: shirt-blue.medium, company: 01, store: 089')
在SQL Server(2016)中,我尝试使用'shirt-red.large'
来搜索以上列中的完整项目字符串(例如'shirt-blue.small'
,CHARINDEX
等) {1}}和'Item: '
,但出现以下错误
“传递给LEFT或SUBSTRING函数的无效长度参数”
这与', '
在字符串中多次出现有关吗?结果是隔离项目的最佳方法是什么?
答案 0 :(得分:1)
自2016年起,您可以通过string_split()
示例或dbFiddle
Select Item = ltrim(rtrim(replace(b.value,'item:','')))
From Test A
Cross Apply string_split([message],',') b
where charindex('item:',value)>0
返回
Item
shirt-red.large
shirt-red.medium
shirt-blue.small
shirt-blue.medium
注意:如果要查看NULL,请使用Outer Apply
答案 1 :(得分:0)
不确定您的代码是什么,但这应该可以工作
replace(substring([message],charindex('item: ',[message]),len([message]) - charindex(', company',[message])),',','')
或者没有项目
left(substring([message],charindex('item: ',[message]) + 6,99),charindex(',',substring([message],charindex('item: ',[message]) + 6,99)) - 1)
这里正在起作用:
declare @test TABLE ( [message] NVARCHAR(100) NULL)
INSERT INTO @test
values
('Location set to: Loc1, Order: 1, item: shirt-red.large, company: 01, store: 01'),
('Location set to: Loc1, Order: 1, item: shirt-red.medium, company: 01, store: 01'),
('Location set to: Loc2, Order: 220, item: shirt-blue.small, company: 01, store: 089'),
('Location set to: Loc2, Order: 220, item: shirt-blue.medium, company: 01, store: 089')
select
withItem = replace(substring([message],charindex('item: ',[message]),len([message]) - charindex(', company',[message])),',','')
,withoutItem = left(substring([message],charindex('item: ',[message]) + 6,99),charindex(',',substring([message],charindex('item: ',[message]) + 6,99)) - 1)
from @test
答案 2 :(得分:0)
这是一个解决方案:
SELECT SUBSTRING([message],
CHARINDEX('item: ', [message])+6,
CHARINDEX(',',message,CHARINDEX('item: ', [message]))-CHARINDEX('item: ', [message])-6)
FROM test