gpt4 book ai didi

sql - 从sql server中的字符串末尾提取子字符串

转载 作者:行者123 更新时间:2023-12-05 01:02:59 24 4
gpt4 key购买 nike

我有以下字符串:

DECLARE @build_names VARCHAR(5000) = NULL; 

SET @build_names = 'BB10-1_X-4759-566549';

我想从最后提取它,- 是分隔符。该字符串将被提取为 3 个子字符串,即 5665494759BB10-1_X

请帮帮我,我是初学者。

最佳答案

您可以使用 charindex()reverse() 来获得您想要的结果:

declare @temp varchar(40)
set @temp = 'BB10-1_X-4759-566549'

select @temp, REVERSE(@temp)
select REVERSE(substring(REVERSE(@temp),0,CHARINDEX('-',REVERSE(@temp),0)))

试一试。它回答了您从字符串的最后一个 - 之后提取的第一个问题。

您问题的下一部分似乎表明您想根据 - 拆分整个内容。使用存储过程或函数将失败,因为您希望 BB10-1_X 是单个字符串。因此,如果这些字符串始终采用恰好具有三个 - 的格式,但您只需要 3 个子字符串,则可以像这样对其进行硬编码。

declare @temp varchar(40), @reverse varchar(40), @sub1 varchar(20), @sub2 varchar(20), @sub3 varchar(20)

SET @temp = 'BB10-1_X-4759-566549'
SET @reverse = REVERSE(@temp)

SET @sub3 = REVERSE(substring(@reverse,0,CHARINDEX('-',@reverse,0)))

SELECT @temp = substring(@temp,0,charindex(REVERSE(substring(@reverse,0,CHARINDEX('-',@reverse,0))),@temp,0)-1)
SELECT @reverse = REVERSE(@temp)

SET @sub2 = REVERSE(SUBSTRING(@reverse,0,CHARINDEX('-', @reverse, 0)))
SET @sub1 = REVERSE(SUBSTRING(@reverse,CHARINDEX('-',@reverse,0)+1,LEN(@temp)-CHARINDEX('-',@reverse,0)))

select @sub1, @sub2, @sub3

关于sql - 从sql server中的字符串末尾提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23088022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com