我有一个字符串,我想用逗号后的第三个字。
id String
1 India,Pakistan,China,Turkey,England
2 USA,UK,Pakistan,India
3 China,North Korea,Turkey,Iran
所需的结果将是
id String
1 China
2 Pakistan
3 Turkey
答案 0 :(得分:1)
您可以像这样使用xml value
DECLARE @SampleData AS TABLE
(
Id int IDENTITY (1,1),
String varchar(200)
)
INSERT INTO @SampleData
VALUES (' India,Pakistan,China,Turkey,England'), ('USA,UK,Pakistan,India'),('China,North Korea,Turkey,Iran')
;WITH temps AS
(
SELECT sd.Id ,CAST('<x>' + replace(sd.String, ',', '</x><x>') + '</x>' as xml) AS String
FROM @SampleData sd
)
SELECT t.Id, t.String.value('(/x)[3]','varchar(50)')
FROM temps t
答案 1 :(得分:0)
使用
可以实现所需的输出语法:
SELECT COALESCE(LTRIM(CAST(('<X>'+REPLACE(<column_name>,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[3]', 'varchar(100)')), '') AS String
FROM <table_name>
问题中表格的自定义查询:
SELECT id,
COALESCE(LTRIM(CAST(('<X>'+REPLACE(String,',' ,'</X><X>')+'</X>') AS XML).value('(/X)[3]', 'varchar(100)')), '') AS String
FROM table_1