SQLserver如何把一列数据分成几列
比如:
列1
订单号,商品编号,商品名称
1, 101 , '手机'
2, 102 , '电脑'
3, 103 ,‘笔记本’
(这些数据都在一列哦)
结果是要让他们分列订单号一列,商品编码一列,商品名称一列
[最优解释]
用函数可以。
if OBJECT_ID('test') is not null
drop table test
if OBJECT_ID('split') is not null
drop function split
go
create table test(col varchar(100))
insert into test
select '1, 101 , ''手机''' union all
select '2, 102, ''电脑''' union all
select '3, 103,''笔记本'''
go
create function split(@str varchar(100))
returns @tab table(id int identity(1,1),val varchar(10))
as begin
declare @val varchar(10),@ind int
set @ind=charindex(',',@str)
while @ind>0
begin
set @val=left(@str,@ind-1)
set @str=right(@str,len(@str)-@ind)
set @ind=charindex(',',@str)
insert into @tab
values(@val)
end
if @ind=0
set @val=@str
insert into @tab
values(@val)
return
end
go
select 订单号=(select val from dbo.split(col) where ID=1),商品编号=(
select val from dbo.split(col) where ID=2),商品名称=(select val from dbo.split(col) where ID=3)
from test
/*
(3 row(s) affected)
订单号 商品编号 商品名称
---------- ---------- ----------
1 101 '手机'
2 102 '电脑'
3 103 '笔记本'
(3 row(s) affected)
*/