基于稀释剂拆分列值并显示在不同的列中

时间:2015-08-11 10:06:59

标签: sql sql-server

我有一个场景如下: 我有一个返回数据的查询如下: 查询示例:

create view testview as
Select
job_id as jobno,
element as elementvalue
from job as j
left outer join elements e on e.fid = j.id 

查询结果

job no      Element value
1           ABC=123|DEF=452|PUT=562
2           ABC=456|HJK=562

但是数据需要显示如下:

job no      Element code      Element Value
1              ABC                123
1              DEF                452
1              PUT                562
2              ABC                456
2              HJK                562 

我有这个功能,但是我无法在提到的第一个查询中使用它。

CREATE FUNCTION testsplitData
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
    WITH Split(stpos,endpos)
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = @ValuePK,
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)

请指导

1 个答案:

答案 0 :(得分:3)

更好的Split功能版本:

ALTER FUNCTION [dbo].[Split]
(
  @delimited nvarchar(max),
  @delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
  id int identity(1,1), -- I use this column for numbering splitted parts
  val nvarchar(max)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select
    r.value('.','varchar(max)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END

测试数据

DECLARE @TABLE TABLE (jobno INT , Elementvalue VARCHAR(1000))
INSERT INTO @TABLE VALUES 
(1 ,'ABC=123|DEF=452|PUT=562'),
(2 ,'ABC=456|HJK=562')

查询

SELECT jobno 
     , LEFT(Val , 3) AS ElementCode
     , RIGHT(Val , 3) AS ElementValue 
FROM @TABLE t 
  CROSS APPLY [dbo].[Split](t.Elementvalue , '|')

结果

╔═══════╦═════════════╦══════════════╗
║ jobno ║ ElementCode ║ ElementValue ║
╠═══════╬═════════════╬══════════════╣
║     1 ║ ABC         ║          123 ║
║     1 ║ DEF         ║          452 ║
║     1 ║ PUT         ║          562 ║
║     2 ║ ABC         ║          456 ║
║     2 ║ HJK         ║          562 ║
╚═══════╩═════════════╩══════════════╝