当前位置: 代码迷 >> Sql Server >> sql server怎么分割数据
  详细解决方案

sql server怎么分割数据

热度:78   发布时间:2016-04-24 23:50:36.0
sql server如何分割数据?
列test中数据格式为
 testa----test1
 testb----test2
 testc----test3
每行数据 都有分割符号---- 。
现在想将test里的数据分割到  user  和 xingming 列中。

sql语句如何实现?

------解决方案--------------------
select substring(col,0,charindex('----',col)) as [USER],REVERSE 
(substring(REVERSE (col),0,charindex('----',REVERSE(col) ))) AS xingming 
from TB

/*
USER xingming
testa test1
testb test2
testc test3*/

------解决方案--------------------
USE test
GO

-->生成表tb

if object_id('tb') is not null 
drop table tb
Go
Create table tb([test] nvarchar(14),[user] nvarchar(50),[xingming] nvarchar(50))
Insert into tb
Select N'testa----test1',null,null
Union all Select N'testb----test2',null,null
Union all Select N'testc----test3',null,null

UPDATE tb
SET [user]=LEFT(test,CHARINDEX('-',test)-1)
,xingming=RIGHT(test,CHARINDEX('-',REVERSE(test))-1)

select * from tb

/*
test           user   xingming
-------------- ------ ---------
testa----test1 testa  test1
testb----test2 testb  test2
testc----test3 testc  test3
*/

Go
  相关解决方案