SQL Server SQL query to pick only the last part of Post_Code column [duplicate]

vfh0ocws  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(101)

This question already has answers here:

Substring after a space (3 answers)
Closed 21 days ago.

I've seen a few of these questions asked but haven't spotted one that's helped!! I'm trying to select the second part of postcode only.

For example Post_Code :

'SF87 5NT'

So here I would like my SQL query to only return '5NT'

3lxsmp7m

3lxsmp7m1#

Here are a few options:

declare @Code varchar(50) = 'SF87 5N6'

select
    stuff(@Code, 1, charindex(' ', @Code) , ''),
    substring(@Code, charindex(' ', @Code) + 1, len(@Code)),
    right(@Code, len(@Code) - charindex(' ', @Code)),
    parsename(replace(@Code, ' ', '.'), 1)

I personally like the stuff approach best when I need to get everything after a certain point. The substring approach is probably about as good (and more flexible if you need to excise a chunk with stuff after it). The last two, I would not probably recommend, since they're kind of like going around your back to get to your elbow, but they do show some additional ways can manipulate the string.

相关问题