我想在Sql Server 2008中用';'分隔的單個表中將兩列分成兩行。請幫我解決這個問題。 列,如:單列到sqlserver中的行
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
我想在Sql Server 2008中用';'分隔的單個表中將兩列分成兩行。請幫我解決這個問題。 列,如:單列到sqlserver中的行
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
首先,你將需要一個分裂的功能,例如:
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個集使用交叉申請是必要的,你想在返回行
希望這每個列有助於
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)
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
的[拆分逗號分隔的字符串錶行到使用TSQL不同的行]可能的複製(https://stackoverflow.com/questions/30920483/split-comma-separated-string-table-row-into-獨立型行美荷蘭國際集團,TSQL) –