Reputation: 3492
How to filter a string in SQL 2008?
SELECT FileName=reverse(left(reverse('\\PRODSERVER\D$\EXPORT\Data20160401.txt'),
charindex('\',reverse('\\PRODSERVER\D$\EXPORT\Data20160401.txt'),
1) - 1))
Above query returns the file name which is Data20160401.txt.
I need to fetch only the server name which is PRODSERVER.
Upvotes: 0
Views: 2544
Reputation: 2465
Asuming the path of your file always starts with \\ you could do something like:
Filename=substring(string,0,charindex(substring(string,2,len(string)-2),'\')
Don't know if this is the exact correct syntax as I am not on a machine with any sql processor at the moment but it should do something like this:
Upvotes: 0
Reputation: 749
DECLARE @path VARCHAR(50) = '\\PRODSERVER\D$\EXPORT\Data20160401.txt'
Select SubString(@path,3,(CHARINDEX('\',@path,3)-3))
Upvotes: 1
Reputation: 6764
Create a function to split your string
CREATE FUNCTION [dbo].[fnSplitString]
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
INSERT INTO @output (splitdata)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END
Invoke the function
select *from dbo.fnSplitString('\\PRODSERVER\D$\EXPORT\Data20160401.txt','\')
Output
PRODSERVER
D$
EXPORT
Data20160401.txt
Upvotes: 1