SQL Server - 选择最后一个连字符之后的所有字符的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31656884/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:51:09  来源:igfitidea点击:

SQL Server - select substring of all characters following last hyphen

sqlsql-serversubstring

提问by EvanMPW

I am working with a database of products, trying to extract the product color from a combined ID/color code column where the color code is always the string following the last hyphen in the column. The issue is that the number of hyphens, product ID, and color code can all be different.

我正在使用产品数据库,尝试从组合的 ID/颜色代码列中提取产品颜色,其中颜色代码始终是列中最后一个连字符后面的字符串。问题是连字符的数量、产品 ID 和颜色代码都可能不同。

Here are four examples:

下面是四个例子:

ABC123-001
BCD45678-0165
S-XYZ999-M2235
A-S-ABC123-001

The color codes in this case would be 001, 0165, M2235, and 001. What would be the best way to select these into their own column?

在这种情况下,颜色代码是0010165M2235,和001。将这些选择到他们自己的列中的最佳方法是什么?

回答by Gordon Linoff

I think the following does what you want:

我认为以下做你想要的:

select right(col, charindex('-', reverse(col)) - 1)

In the event that you might have no hyphens in the value, then use a case:

如果值中可能没有连字符,请使用case

select (case when col like '%-%'
             then right(col, charindex('-', reverse(col)) - 1)
             else col
        end)

回答by rchacko

It is great to check whether the hyphen exists or not in the string, to avoid the following error:

最好检查字符串中是否存在连字符,以避免出现以下错误:

Invalid length parameter passed to the right function.

传递给正确函数的长度参数无效。

SELECT CASE WHEN Col like '%\%' THEN RIGHT(Col,CHARINDEX('\',REVERSE(Col))-1) ELSE '' END AS ColName