Get everything after and before certain character in SQL Server

前端 未结 15 1926
臣服心动
臣服心动 2020-12-07 18:48

I got the following entry in my database:

images/test.jpg

I want to trim the entry so I get: test

So basically, I want

15条回答
  •  情歌与酒
    2020-12-07 19:23

    If you want to get this out of your table using SQL, take a look at the following functions that will help you: SUBSTRING and CHARINDEX. You can use those to trim your entries.

    A possible query will look like this (where col is the name of the column that contains your image directories:

    SELECT SUBSTRING(col, LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) + 1, 
        LEN(col) - LEN(SUBSTRING(col, 0, LEN(col) - CHARINDEX ('/', col))) - LEN(SUBSTRING(
        col, CHARINDEX ('.', col), LEN(col))));
    

    Bit of an ugly beast. It also depends on the standard format of 'dir/name.ext'.

    Edit:
    This one (inspired by praveen) is more generic and deals with extensions of different length:

    SELECT SUBSTRING(col, LEN(LEFT(col, CHARINDEX ('/', col))) + 1, LEN(col) - LEN(LEFT(col, 
        CHARINDEX ('/', col))) - LEN(RIGHT(col, LEN(col) - CHARINDEX ('.', col))) - 1);
    

提交回复
热议问题