How do I split a string so I can access item x?

2018-12-30 22:57发布

Using SQL Server, how do I split a string so I can access item x?

Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?

38条回答
与风俱净
2楼-- · 2018-12-30 23:27
皆成旧梦
3楼-- · 2018-12-30 23:28

What about using string and values() statement?

DECLARE @str varchar(max)
SET @str = 'Hello John Smith'

DECLARE @separator varchar(max)
SET @separator = ' '

DECLARE @Splited TABLE(id int IDENTITY(1,1), item varchar(max))

SET @str = REPLACE(@str, @separator, '''),(''')
SET @str = 'SELECT * FROM (VALUES(''' + @str + ''')) AS V(A)' 

INSERT INTO @Splited
EXEC(@str)

SELECT * FROM @Splited

Result-set achieved.

id  item
1   Hello
2   John
3   Smith
查看更多
登录 后发表回答