如何在SQL QUERY中进行SUBSTRING

时间:2015-11-24 11:36:48

标签: sql sql-server-2008-r2

21699,21712

我需要一个子串输出为21712

1 个答案:

答案 0 :(得分:1)

只需检查此示例,您必须使用charindex(查找逗号索引)和substring函数来获取子字符串值

Declare @var varchar(50) = '21699,21712'
select charindex( ',', @var), substring ( @var, charindex(',', @var)+1, len(@var))

您也可以使用它:

declare @var varchar(50) = '21699,21712'
select charindex( ',', @var), substring ( @var, charindex(',', @var)+1, len(@var))

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    @var name,
    CONVERT(XML,'<Names><name>' + REPLACE(@var,',', '</name><name>') + '</name></Names>') AS xmlname      
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS part1,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS part2
 FROM Split_Names