How to split strings in SQL Server

 ̄綄美尐妖づ 提交于 2020-01-11 04:21:05

问题


I have the following input:

Data
-----
A,10
A,20
A,30
B,23
B,45

Expected output:

col1  Col2
----  -----
A      10
A      20
A      30
B      23
B      45

How can I split the string to produce the desired output?


回答1:


SELECT substring(data, 1, CHARINDEX(',',data)-1) col1,
substring(data, CHARINDEX(',',data)+1, LEN(data)) col2
FROM table



回答2:


I know the points has already been given, going to post it anyway because i think it is slightly better

DECLARE @t TABLE (DATA VARCHAR(20))

INSERT @t VALUES ('A,10');INSERT @t VALUES ('AB,101');INSERT @t VALUES ('ABC,1011')

SELECT LEFT(DATA, CHARINDEX(',',data) - 1) col1, 
RIGHT(DATA, LEN(DATA) - CHARINDEX(',', data)) col2
FROM @t



回答3:


declare @string nvarchar(50)
set @string='AA,12'

select substring(@string,1,(charindex(',',@string)-1) ) as col1 
, substring(@string,(charindex(',',@string)+1),len(@string) ) as col2![my sql server image which i tried.][1]



回答4:


if the values in column 1 are always one character long, and the values in column 2 are always 2, you can use the SQL Left and SQL Right functions:

SELECT LEFT(data, 1) col1, RIGHT(data, 2) col2
FROM <table_name>



回答5:


it is so easy, you can take it by below query:

SELECT LEFT(DATA, CHARINDEX(',',DATA)-1) col1,RIGHT(Data,LEN(DATA)-(CHARINDEX(',',DATA))) col2 from Table


来源:https://stackoverflow.com/questions/6619810/how-to-split-strings-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!