如何通过使用SQL查询将行字符串值转换为列

时间:2018-11-09 06:26:39

标签: sql-server

如何在SQL Server中实现以下要求。

数据我所拥有的:

Table A(Input

,预期输出为:

Table B(Expected Output

谢谢, 劳伦斯A

2 个答案:

答案 0 :(得分:0)

假设您给定的数据值:

 'Message:"A",Level:"0",type:"log"'
 'Message:"B",Level:"1",type:"log"'

select substring(ColumnA,10,1) Message,
replace(dbo.udf_GetNumeric(replace(replace(substring(ColumnA,20,5),'"',''),',','')),' ','')[type],
replace(replace(substring(ColumnA,29,250),'"',''),',','')[Log] from YourTable

GetNumeric here

答案 1 :(得分:0)

我创建了两个函数来实现所需的输出。 通过创建两个函数splitgetVal

使用以下查询
select 
    dbo.getVal(columnA,'Message') Message,
    dbo.getVal(columnA,'Level') [Level],
    dbo.getVal(columnA,'type') [type]
from TableA

查询创建splitgetVal函数

Create function split(@s varchar(500),@splitWith varchar(20))
returns @RetTable Table(id int identity(1,1), Value varchar(200))
as
begin
    if(CHARINDEX(@splitWith,@s)>0)
    begin
    set @s=@s+@splitWith
        declare @len int =len(@s)
        while charindex(@splitWith,@s)>0
        begin
            insert @RetTable values(SUBSTRING(@s,1,charindex(@splitWith,@s)-1))
            set @s=SUBSTRING(@s,charindex(@splitWith,@s,1)+1,@len)
        end
    end
    return
end



 Create function getVal(@str varchar(500),@column varchar(200))
    returns varchar(200)
    as
    begin
    declare @ret varchar(200)
        select @ret=value From dbo.split((select value From dbo.split('Message:"A",Level:"0",type:"log"',',') where value like +@column+'%'),':') where id=2
        return replace(@ret,'"','')
    end