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
/*
USERxingming
testatest1
testbtest2
testctest3*/
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