我尝试从我的字符串中提取最后一个单词
例
输入字符串:GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD
结果
╔═══════════╦════════════╗ ║ FIRST_COL ║ SECOND_COL ║ ╠═══════════╬════════════╣ ║ CCC ║ DDDDD ║ ╚═══════════╩════════════╝
我有以下代码工作.
DECLARE @STR VARCHAR(50) = 'GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD' SELECT Reverse(LEFT(Stuff(Reverse(@STR),1,Charindex('_',Reverse(@STR)) + 1 - 1,''),Stuff(Reverse(@STR),'')) - 1)) as FIRST_COL,Reverse(LEFT(Reverse(@STR),Reverse(@STR)) - 1)) as SECOND_COL
有没有更简单的实现这一点
解决方法
您可以使用XML:
DECLARE @input nvarchar(max) = 'GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD',@x xml SELECT @x = CAST('<a>'+REPLACE(REVERSE(@input),'_','</a><a>')+'</a>' as xml) SELECT REVERSE(@x.value('/a[2]','nvarchar(max)')) as FIRST_COL,REVERSE(@x.value('/a[1]','nvarchar(max)')) as SECOND_COL
输出:
FIRST_COL SECOND_COL CCC DDDDD