日期:2014-05-17  浏览次数:20583 次

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)

*/

------其他解决方案--------------------
那就等等大神 有什么高招吧 我也学习下
------其他解决方案--------------------
原始数据里 有逗号分割没?
------其他解决方案--------------------

[quote=引用:]
原始数据里 有逗号分割没?[有
------其他解决方案--------------------
有逗号分隔

引用:
[quote=引用:]
原始数据里 有逗号分割没?[有

------其他解决方案--------------------
declare @A char(20)
set @A='hao,xue,xi'
select left(@A,charindex(',',@A)-1),left(substring(@A,charindex(',',@A)+1,len(@A)-charindex(',',@A)),charindex(',',substring(@A,charindex(',',@A)+1,len(@A)-charindex(',',@A)))-1)
,reverse(left(reverse(@A),charindex(',',reverse(@A))-1))
这个有点复杂 应该还有更简单的。
------其他解决方案--------------------
引用:
declare @A char(20)
set @A='hao,xue,xi'
select left(@A,charindex(',',@A)-1),left(substring(@A,charindex(',',@A)+1,len(@A)-charindex(',',@A)),charindex(',',substring(@A,charindex(',',@A)……

我的数据量很大,这个应该不可以。。。