declare @mydata nvarchar(4000)
set @mydata = '36|0, 77|5, 132|61'
我有这个数据需要进入表格。因此对于Row1 columnA将是36而columnB将是0.对于Row2 columnA将是77而columnB将是5等。
最好的方法是什么?
由于
答案 0 :(得分:1)
您需要一个拆分表值函数。网上有很多例子,例如: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648
CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
go
declare @mydata nvarchar(4000)
set @mydata = '36|0, 77|5, 132|61'
select
rowid, [1] as col1, [2] as col2
from
(
select
Row.Id as rowid, Col.Id as colid, Col.Data
from dbo.Split(@mydata, ',') as Row
cross apply dbo.Split(Row.Data, '|') as Col
) d
pivot
(
min(d.data)
for d.colid in ([1], [2])
) pd
我刚刚选择了我发现的第一个分割功能。我不认为它是最好的,但它适用于这个例子。
输出:
rowi col1 col2 1 36 0 2 77 5 3 132 61
答案 1 :(得分:1)