从我的字符串中提取最后两个单词

时间:2016-09-28 10:18:53

标签: sql sql-server tsql

我尝试从我的字符串中提取最后一个单词。

实施例

输入字符串: 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, ''), Charindex('_', Stuff(Reverse(@STR), 1, Charindex('_', Reverse(@STR)) + 1 - 1, '')) - 1)) as FIRST_COL,
Reverse(LEFT(Reverse(@STR), Charindex('_', Reverse(@STR)) - 1)) as SECOND_COL

有没有更简单的方法来实现这个

5 个答案:

答案 0 :(得分:6)

您可以使用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

答案 1 :(得分:3)

您可以使用class User < ApplicationRecord has_many :downloadable_documents has_many :documents, through: :downloadable_documents end class DownloadableDocuments < ApplicationRecord belongs_to :user belongs_to :document end class Document < ApplicationRecord has_many :downloadable_documents has_many :users, through: :downloadable_documents end (从2012年开始)

PARSENAME

注意:对于超过3 DECLARE @Val NVARCHAR(100)= 'AAAA_BBB_CCC_DDDDD' SELECT PARSENAME(REPLACE(@Val, '_', '.'), 1) -- DDDDD SELECT PARSENAME(REPLACE(@Val, '_', '.'), 2) -- CCC

,这是不正确的

答案 2 :(得分:2)

Declare @Var1  VARCHAR(MAX)='AAAA_BBB_CCC_DDDDDDD'

----SELECT CHARINDEX('_',REVERSE(@Var1))
SELECT RIGHT(@Var1,CHARINDEX('_',REVERSE(@Var1))-1)


-----SELECT REPLACE(@Var1,RIGHT(@Var1,CHARINDEX('_',REVERSE(@Var1))),'')

--SELECT CHARINDEX('_',REVERSE(
--  REPLACE(@Var1,RIGHT(@Var1,CHARINDEX('_',REVERSE(@Var1))),'')
--))

SELECT RIGHT(
REPLACE(@Var1,RIGHT(@Var1,CHARINDEX('_',REVERSE(@Var1))),''),
CHARINDEX('_',REVERSE(
    REPLACE(@Var1,RIGHT(@Var1,CHARINDEX('_',REVERSE(@Var1))),'')
))-1)

答案 3 :(得分:1)

您可以使用用户定义的自定义函数,如下所示

DECLARE @Val NVARCHAR(100)= 'AAAA_BBB_CCC_DDDDD'
;with cte as (
    select id, val, MAX(id) over (partition by 1) maximum 
    from dbo.SQLSplitString(@Val,'_',1,0) t
)
select val from cte where id >= maximum - 1

您可以在这里找到SQL split function codes

答案 4 :(得分:1)

试试这个:存储字符串时,将其存储为反转,以减少必要的调用以使字符串反转

DECLARE @STR VARCHAR(50) =REVERSE('GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD')

SELECT REVERSE(SUBSTRING(@STR,0, CHARINDEX('_',@STR))),
       REVERSE(SUBSTRING(@STR,CHARINDEX('_',@STR,CHARINDEX('_',@STR))+1,3))