SQL 子串和最后一个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2919727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Substring and Last index of
提问by Max Al Farakh
i've got stuck with substring.
我被子字符串卡住了。
On input i've got a string that looks like Sometext (123456)
. Those digits at the end are random. I need to get only text from that string.
在输入时,我有一个看起来像Sometext (123456)
. 末尾的那些数字是随机的。我只需要从该字符串中获取文本。
回答by AdaTheDev
How about this?
这个怎么样?
DECLARE @Data TABLE (Val VARCHAR(20))
INSERT @Data VALUES ('Sometext (123456)')
INSERT @Data VALUES ('')
INSERT @Data VALUES (NULL)
INSERT @Data VALUES ('S(123456)')
INSERT @Data VALUES ('(123456)')
SELECT
CASE
WHEN CHARINDEX('(', Val) > 0 THEN
RTRIM(SUBSTRING(val,1, CHARINDEX('(', Val) - 1))
ELSE Val
END
FROM @Data
回答by Tuan Zaidi
If we want to remove the sentence and keep the number we might do like this.
如果我们想删除句子并保留数字,我们可能会这样做。
DECLARE @Text VARCHAR(MAX);
SET @Text = 'Sometext (123456)'
SELECT SUBSTRING(@Text, CHARINDEX(' ', @Text) + 1, LEN(@Text)) As TextOutput
The result will be: (123456)
结果将是:(123456)
回答by eddiegroves
It really does depend on the format of your input string, but here is a slightly different approach using PATINDEXthat will return the string until it matches a non A-Z character:
它确实取决于您输入字符串的格式,但这里使用PATINDEX 的方法略有不同,它将返回字符串,直到与非 AZ 字符匹配:
declare @text varchar(500); set @text = 'Sometext (123456)'
select SUBSTRING(@text, 0, PATINDEX('%[^A-Z]%' , @text))
回答by edosoft
If you just want the first part up to the '(' you could try
如果你只想要第一部分到 '(' 你可以试试
declare @t varchar(50)
set @t = 'function (12343)'
select rtrim(substring(@t,1, charindex('(', @t)-1))