单列到sqlserver中的行

时间:2017-09-08 07:05:00

标签: sql-server-2008

我想在Sql Server 2008中用';'分隔的单个表中将两列拆分为两行。请帮我解决这个问题。 列如:

1;2;3;4;5;6;7; and a;b;c;d;e;f;g;

输出行如:

1   a
2   b
3   c
4   d
5   e
6   f
7   g

3 个答案:

答案 0 :(得分:1)

首先,你需要一个分割功能:

CREATE function [dbo].[Split]
(
@string nvarchar(max),
@delimiter nvarchar(20)
)
returns @table table
(
   [Value] nvarchar(max)
)
begin
declare @nextString nvarchar(max)
declare @pos int, @nextPos int

  set @nextString = ''
  set @string = @string + @delimiter

  set @pos = charindex(@delimiter, @string)
  set @nextPos = 1
  while (@pos <> 0)
  begin
      set @nextString = substring(@string, 1, @pos - 1)

      insert into @table
      (
          [Value]
      )
      values
      (
          @nextString
      )

      set @string = substring(@string, @pos + len(@delimiter), len(@string))
      set @nextPos = @pos
      set @pos = charindex(@delimiter, @string)
  end
  return
end

然后使用此代码:

 SELECT col1.Value as val1,
        col2.Value as val2          
 FROM
    (SELECT  Value,
             ROW_NUMBER() over(order by value asc) as rownum
     FROM (
        VALUES('1;2;3;4;5;6;7')
        ) valued(X) CROSS APPLY 
            DBO.SPLIT(X,';') AS SPLITEDCOL ) as col1 INNER JOIN
    (SELECT  Value,
             ROW_NUMBER() over(order by value asc) as rownum
     FROM (
        VALUES('A;B;C;D;E;F;G')
        ) valued1(X) CROSS APPLY 
            DBO.SPLIT(X,';') AS SPLITEDCOL ) as col2
    ON COL1.rownum = col2.rownum

如果您的两列来自表格,您可以选择它们:

 SELECT  Value,
         ROW_NUMBER() over(order by value asc) as rownum
 FROM YourTable CROSS APPLY 
        DBO.SPLIT(YourColumnName,';') AS SPLITEDCOL

请注意,对于要按行返回的每列,需要使用交叉应用的1个子集

希望这有帮助

答案 1 :(得分:0)

Declare @ID as Varchar(1000)
set @ID = '1;2;3;4;5;6;7;'
SELECT 
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS ID
FROM
(
SELECT CAST('<XMLRoot><RowData>' + REPLACE(@ID,';','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)

答案 2 :(得分:0)

DECLARE @Table1 TABLE(ID INT, Value char)
INSERT INTO @Table1 VALUES (1,'a'),(1,'b'),(1,'c'),(1,'d')


SELECT  STUFF((SELECT '; ' + CAST(ID AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') ID
       ,STUFF((SELECT '; ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') value
FROM @Table1 t