SQL Server - select substring of all characters fo

2019-07-06 16:44发布

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.

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?

2条回答
ら.Afraid
2楼-- · 2019-07-06 17:22

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
查看更多
霸刀☆藐视天下
3楼-- · 2019-07-06 17:29

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:

select (case when col like '%-%'
             then right(col, charindex('-', reverse(col)) - 1)
             else col
        end)
查看更多
登录 后发表回答