Remove the last character in a string in T-SQL?
When your adventures in T-SQL land you in the need to trim off the final character from a sting:
Peel off column
and table
labels and slap on your actual column and table names. And, bam! You're done.
Tackling NULLs and edge cases
Working with strings is not all rainbows 🌈 and unicorns 🦄. NULL values can leap out of nowwhere causing a ruckus in your query results. Here's how you write the equivalent of a "I have an unhealthily high self-esteem" pep talk for your strings:
Preventing NULL value freak-outs is just one of those T-SQL best practices, make sure you've got it under your belt.
Re-use friendly for coding magnates
If you're a coding magnate with starry-eyed dreams of reusability, here's a function for the job:
Wrap that function around your queries like a cosy blanket:
The atypical family - alternatives to LEFT and LEN
Not a fan of LEFT
and LEN
? No worries, T-SQL's got you covered with a bunch of their lesser-known cousins who can do the job just as well:
- REVERSE and STUFF: The cool kids on the block when dealing with variable-length strings or multi-occurence logic within a query.
-
SUBSTRING: This one's an introvert - keeps to itself, but gets the job done with precision when asked to adjust lengths.
In all cases, the NULL and empty string check still applies. Yes, you gotta cover your bases.
Repetition is not your friend
If you're working with complex logic or recurrent computation within a query, avoid rehashing trimming logic. Use a CTE (Common Table Expression) or a subquery to condense it, like so:
Clean queries are happy queries. Keep them tidy, make them smile.
Unwanted guests—empty strings
Empty strings are like ghosts in your code, causing inexplicable errors. Trail them with LEN
and NULLIF:
This way, you're not trying to trim what's already bald, preserving the wholesomeness of data set.
Considerations for the big guys
Handling VARCHAR(MAX) or NVARCHAR(MAX) types? Remember, size does matter:
Remember to wear your big data handling gloves while at it ✋🔥!
Was this article helpful?