在 T-SQL 中获取字符串的某个部分 [英] Getting a certain part of the string in T-SQL
问题描述
我有一个像 prop234
这样的字符串,字母部分有固定长度,但数字部分可以是任意长度
I have a string like prop234
the alphabet part has fixed length but the numeric part may be of any length
我必须从 T-SQL 中的字符串中获取数字部分(在 SQL Server 2008 上)
I have to get the numeric part from the string in T-SQL (on SQL Server 2008)
我尝试使用 SUBSTRING
函数,但我不知道数字部分的长度,因此无法提供第三个参数,即长度
I tried with SUBSTRING
function but I don't know the length of the numeric part so can't provide third parameter i.e. length
SUBSTRING ( expression ,start , length )
我知道起始索引,但长度可以是任何
I know the start index but length can be anything
一种解决方案是
SELECT substring([ColumnName], 5, LEN(ColumnName) - 4)
因为起始索引是固定的,即字母部分的长度是 4(固定)
as start index is fixed i.e. length of alphabet part is 4 (fixed)
有没有更好的解决方案,如果字母部分的长度不是恒定的怎么办?
Is there any better solution for this and what if the length of alphabetic part is not constant?
推荐答案
select stuff('prop234', 1,4,'')
如果长度不是常数:
declare @t table(expression varchar(100))
insert @t values('propprop234')
select stuff(expression, 1, patindex('%_[0-9]%', expression), '') from @t
为了确保处理不好的数据,例如没有文本第一或最后没有数字,这里有一个稍微不同的方法:
To make sure bad data is handled, such as no text first or no number last, here is a slightly different approach:
select stuff(expression, 1,patindex('%[^0-9][0-9]%', expression + '0'), '')
from @t
这篇关于在 T-SQL 中获取字符串的某个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!