开发者

T SQL how to modify a string by removing all the part after the last delimiter

I'm struggling to find the righ开发者_如何学Pythont functions with SQL Server 2008 to rectify any strings coming like: \\myserver\mydir1\dir2\test.txt or \\myserver2\dir1\dir2\dir3\test.txt.

At the end, the result should appear like: \\myserver\mydir1\dir2 or \\myserver2\dir1\dir2\dir3 , So after the last "\" , the substring should be removed.

Any idea how to do that?


DECLARE @urls TABLE (URL varchar(2000))

INSERT @urls VALUES ('\\myserver\mydir1\dir2\test.txt')
INSERT @urls VALUES ('\\myserver2\dir1\dir2\dir3\test.txt')

SELECT
    REVERSE(SUBSTRING(REVERSE(URL), CHARINDEX('\', REVERSE(URL))+1, 8000))
FROM
    @urls

Logic:

  • \\myserver\mydir1\dir2\test.txt
  • REVERSE = txt.tset\2rid\1ridym\revresym\
  • look for first \
  • take everything after that SUBSTRING = 2rid\1ridym\revresym\
  • REVERSE = \\myserver\mydir1\dir2

You don't need to know the LEN of the string for the SUBSTRING so just use 8000

Edit, after comment about using 8000

  1. You can use 2147483647 in SUBSTRING because it supports max types
  2. Only has to be equal to or longer that the varchar variable or column length
  3. What about the overhead of calculating LEN?
  4. Practically all URLs have to fit into 2083 bytes
  5. Does it matter? "Premature optimisation" etc


DECLARE @input VARCHAR(50)
SET @input = '\\myserver\mydir1\dir2\test.txt'

SELECT SUBSTRING(@input, 1, LEN(@input) - CHARINDEX('\', REVERSE(@input)));


DECLARE @s VarChar(100) = '\myserver\mydir1\dir2\test.txt';

DECLARE @length Int = LEN(@s),
        @position Int = CHARINDEX('\', REVERSE(@s));

SELECT SUBSTRING(@s, 1, @length - @position);


Try something like this...

SELECT CASE SUBSTRING ( [yourField], LEN([yourField])-2, LEN([yourField])-1)
WHEN '\' THEN (SUBSTRING ( [yourField], 0, LEN([yourField])-1))
ELSE [yourField]

End
  FROM [yourTable]
GO

Hope that helps,

Jeffrey Kevin Pry

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜