我在SQL Server中有一个字符串字段,其中包含一些我想要分成不同字段的项目。其中两个包含双引号。以下是该领域存在的一个例子。这都是一个字符串
示例: 111668999 555444888“3 LOW”“5 HIGH”
我想要做的是将“3 LOW”和“5 HIGH”分解到他们自己的新字段中,但保留它们周围的引号。我已经成功地分离了它们的数值,所以我只是处理“3 LOW”“5 HIGH”值。我确信它可以通过CHARINDEX和SUBSTRING的组合来完成,但我一直在努力将引号识别为起点和终点,并确保它们仍然包含在新字段中。
谢谢!
答案 0 :(得分:2)
;with tb(s) as (
select '111668999 555444888 "3 LOW" "5 HIGH"'
)
select node from tb
cross apply(values(convert(XML,'<n>'+replace(tb.s,'"','</n><n>')+'</n>'))) as c(x)
cross apply( select x.node.value('.','varchar(20)') as node from c.x.nodes('n') x(node) )as p
where patindex('[0-9] [a-Z]%', p.node)>0
node 1 3 LOW 2 5 HIGH
答案 1 :(得分:1)
您可以创建此功能
CREATE FUNCTION [dbo].[SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(3),
@mark nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter
begin
set @iStart = 2
insert into @tParts
values( null )
end
else
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0
insert into @tParts
values ( replace(ltrim(substring( @sString, @iStart, @iPos-
@iStart )) + @mark,'""','"'))
set @iStart = @iPos+1
if @iStart > len( @sString )
break
end
RETURN
END
GO
并以这种方式使用
SELECT * FROM [dbo].[SplitString]
('"3 LOW" "5 HIGH" "7 HIGH" "8 HIGH"','" "', '"')
结果
"3 LOW"
"5 HIGH"
"7 HIGH"
"8 HIGH"
答案 2 :(得分:1)
这会将值放在字段而不是行
中示例强>
Declare @YourTable table (ID int,SomeCol varchar(max))
Insert Into @YourTable values
(1,'111668999 555444888 "3 LOW" "5 HIGH"')
Select A.ID
,B.*
From @YourTable A
Cross Apply (
Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
,Pos2 = '"'+ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
,Pos3 = '"'+ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
From (Select Cast('<x>' + replace((Select replace(A.SomeCol,' "','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as A
) B
<强>返回强>