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.

Getting File's Directory and Parent Directory in SQL Server

As you can see, we have the directory and parent directory of the file.

Good luck to everyone in business and life.

129 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!