Getting File’s Directory and Parent Directory in SQL Server
Hello to everyone,
In this article, I will try to give information about getting the directory and parent directory of the file in SQL Server.
In SQL Server, in some cases you may want to get the directory and parent directory of the file.
You can easily do this using the code below.
DECLARE @path VARCHAR(MAX);
SET @path = 'C:/Users/PC/OneDrive/Masaüstü/yavuzselimkart.txt';
SET @path = CASE
WHEN CHARINDEX('/', @path) = 1 THEN
RIGHT(@path, LEN(@path) - 1)
ELSE
@path
END;
DECLARE @Root VARCHAR(MAX),
@fileName VARCHAR(MAX),
@fileRoot VARCHAR(MAX);
SELECT @Root = LEFT(@path, CHARINDEX('/', @path) - 1),
@fileName = RIGHT(@path, CHARINDEX('/', REVERSE(@path)) - 1),
@fileRoot = LEFT(@path, LEN(@path) - LEN(RIGHT(@path, CHARINDEX('/', REVERSE(@path)) - 1)) - 1);
SELECT ROOT = LEFT(@path, LEN(@Root)),
FileDirectoryRoot = LEFT(@path, LEN(@path) - (CHARINDEX('/', REVERSE(@fileRoot)) + LEN(@fileName) + 1)),
FileDirectory = LEFT(@path, LEN(@fileRoot)),
FileName = RIGHT(@path, LEN(@fileName));
When you run the above code, you will see the following result.
As you can see, we have the directory and parent directory of the file.
Good luck to everyone in business and life.