I am going to continue my series of very short articles or tidbits on Transaction SQL string functions. I will exploring the RIGHT() function today.
The RIGHT() function takes the source string [S] and number of characters [X] as input and returns the [X] rightmost characters from string [S] as output.
The following example grabs the last word from a favorite movie title of mine.
1 2 |
-- Return last word select right('wizard of oz', 2) as str_word |
1 2 3 4 5 |
output: str_word ----------- oz |
One thing to always worry about when using TSQL functions is how will it react with empty strings, NULL values, or invalid values? Both empty strings and NULL values as inputs return themselves as outputs. A negative number for input [X] will result in a error being throw.
1 2 3 4 5 6 7 8 |
-- Invalid length select right('wizard of oz', -1) as str_word -- Empty returns empty select right('', 2) as str_word -- Null returns Null select right(NULL, 6) as str_word |
1 2 3 4 5 6 7 8 9 10 11 |
output: Msg 536, Level 16, State 1, Line 2 Invalid length parameter passed to the right function. str_word -------- str_word -------- NULL |
Next time, I will be exploring the RTRIM() function.