I have two columns (A, B) like this….
A B
12_18_19 20
I want a 3rd column (C) added within same SELECT statement like this…
C
12_18_20_19
in other words, my column A is delimited by “_”, so the second last index of column A should be column B.
If possible I would do do all this within same SELECT statement like this…
A B C
12_18_19 20 12_18_20_19
How about:
It’s a bit involved, mostly also because there is no
LASTCHARINDEX()function in T-SQL.The first expression parses the
Acolumn up to the last_separator characters and takes everything before that. Then it appends a_and columnB, and then grabs everything after that last_separator fromAand appends that.And as Andriy M rightfully mentioned in his comment : if
AorBareNULL, then the whole result is NULL, too. If the columns are empty strings, or ifAdoesn’t contain any_characters, you’ll might get errors (since the parsing will fail) or unexpected, messy results.