2017-08-16 53 views
1

我有一個SQL Server中的字符串字段,其中包含我想分解成單獨字段的幾個項目。其中兩個包含雙引號。以下是該領域存在的一個例子。這一切都是在一個字符串如何根據SQL Server中的字符提取部分字符串?

例子:111668999 555444888「3低」「5 HIGH」

我想什麼做的是打出來的「3低」和「5 HIGH」到他們的擁有新的領域,但保留他們的報價。我已經成功分離了數字值,因此我正在研究「3 LOW」「5 HIGH」值。我確信它可以通過CHARINDEX和SUBSTRING的組合來完成,但我一直在努力將引號確定爲起點和終點,並確保它們仍然包含在新字段中。

謝謝!

回答

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
;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

這將把值字段不排

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 

返回

enter image description here