T-SQL 子字符串 - 最后 3 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8359772/
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
T-SQL Substring - Last 3 Characters
提问by Jared
Using T-SQL, how would I go about getting the last 3characters of a varchar column?
使用 T-SQL,我将如何获取varchar 列的最后 3 个字符?
So the column text is IDS_ENUM_Change_262147_190and I need 190
所以列文本是IDS_ENUM_Change_262147_190,我需要190
回答by JNK
SELECT RIGHT(column, 3)
That's all you need.
这就是你所需要的。
You can also do LEFT()in the same way.
你也可以LEFT()用同样的方法做。
Bear in mind if you are using this in a WHEREclause that the RIGHT()can't use any indexes.
请记住,如果您在不能使用任何索引的WHERE子句中RIGHT()使用它。
回答by Elias Hossain
You can use either way:
您可以使用任何一种方式:
SELECT RIGHT(RTRIM(columnName), 3)
OR
或者
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
回答by Ben Thul
Because more ways to think about it are always good:
因为更多的思考方式总是好的:
select reverse(substring(reverse(columnName), 1, 3))
回答by user2176274
declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))
=== Explanation ===
=== 说明 ===
I found it easier to read written like this:
我发现这样写更容易阅读:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
- Reverse the text
- Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
- Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
- Reversed the reversed string to give you your desired substring
- 反转文本
- 查找特定字符的第一次出现(即第一次出现 FROM END of text)。获取这个字符的索引
- 再次查看反转文本。从索引 0 搜索到您的字符的索引。这给出了您正在寻找的字符串,但反过来
- 反转反转的字符串,为您提供所需的子字符串
回答by sharath
if you want to specifically find strings which ends with desired characters then this would help you...
如果您想专门查找以所需字符结尾的字符串,那么这将对您有所帮助...
select * from tablename where col_name like '%190'

