I have a working version of an extraction step, that seems quite lengthy and I was curious if there's a simpler approach that I may be missing. I've seen SUBSTRING_INDEX() referenced in other questions on the forum, however, that function isn't recognized in my version of Sql Server Management Studio.
I have a string that looks like this: Make\Model\Trim\New
I'd like to extract only the "Trim" from this string. Essentially, extract the substring between the last backslash and the second-to-last backslash.
Because the string length and number of backslashes may vary, I can't simply say "After the second and third backslashes". Below is my currently working code.
Select
REVERSE(SUBSTRING(
REVERSE(CAR_DESC),
CHARINDEX('\',REVERSE(CAR_DESC))+1,
CHARINDEX('\',REVERSE(CAR_DESC),CHARINDEX('\',REVERSE(CAR_DESC))+1)-CHARINDEX('\',REVERSE(CAR_DESC))-1
)) AS TEST1
FROM TABLEA
4条答案
按热度按时间35g0bw711#
Just another option using JSON
Example
Results
Note: I had to escape the backslash, thus the
\\
IF FOUR elements (and no more), you can use
parsename()
z8dt9xmd2#
EDIT - As pointed out in the comments, this will only work with SQL Server 2022 or Azure.
You could do something still pretty ugly with string_split:
Fiddle
You'd be a lot better off storing your data appropriately, as opposed to doing this kind of stuff every time you read the data.
ktecyv1j3#
So this is a bit of a hack (to say the least) but as long as your string isn't really long, and you have fewer than 4 delimiters, you can hack out the pieces using
parsename()
. parsename is a function designed for extracting parts of a fully qualified object name (e.g.server.database.table.schema
or lower cardinality versions of the same).The hack you can do is replace all the slashes in your string with periods, and then extract the names.
Be warned however, if any individual part is longer than 128 characters (i.e. the length of a
sysname
object) all parts will return null (At least I think that's how it works. truthfully, you might want to play around with different lengths of total strings and string parts if you're concerned about either being fairly long).e.g., this works, but if you make one of the strings longer, it fails:
vc9ivgsu4#
I am late to the game, but here is an exact solution for your scenario.
I'd like to extract only the "Trim" from this string. Essentially, extract the substring between the last backslash and the second-to-last backslash.
It is using XML and XQuery, and will work on any version starting from SQL Server 2012 onwards.
Notable points:
CROSS APPLY
is tokenizing input as XML./root/r[last() - 1]
.SQL
Output