I have a column containing value like:
"AAAA\BBBBBBBB\CCC" (A, B, C part length are not fixed.)
I need to trim out the \CCC part if it exists, and leave it alone if not exist.
For example:
AAA\BBBBBB\CCC -> AAA\BBBBBB
AA\BBBB -> AA\BBBB
AA -> AA
Sorry I am not clear enough, the A, B, C parts are not literally ABC, they could be any content.
Also \DDD\EEEE(etc.) should be removed as well
While there's certainly a way to do it in pure T-SQL, it might not be as clear as it could be.
You may want to consider using a SQLCLR-based user defined function (UDF) instead. With that you'll be able to benefit from the power and clarity of c# (or vb.net) within Sql Server.
Just make it so that your function will receive your string as a param and return the output that you want as a scalar value. From then on you'll be able to use that function just like any other UDF you may already have. This way your code would be much easier to write (and read / maintain afterwards).
Your sqlclr function could be as easy to write as this (pseudo code):
Then, from T-SQL:
This page will give you pretty much all you need to get started:
SQL Server Common Language Runtime Integration
You can use
PATINDEX
to find out if the field has 3 (or more) parts, and then some string manipulation to chop off the last part:This is how I would accomplish this task:
Paste this into a query window and give it a shot with different
@temp
values. It does a quick check to see if two'\'
s exist, and trims it to the character place before the second'\'
. If less than two'\'
s exist, it will just return the value itself.Here is a solution to remove the last part if there are two or more parts (separated by \)