devxlogo

How to Read Environment Variables in SQL Server Using T-SQL

How to Read Environment Variables in SQL Server Using T-SQL

To read Environment variables in T-SQL, you can use the xp_cmdshell extended stored procedure in SQL Server.

The following example shows how to read the %windir% environment variable, which gives the Windows directory path on SQL Server using xp_cmdshell:

DECLARE @windir nvarchar(255)CREATE TABLE #Tmp(EnvVar nvarchar(255))INSERT INTO #Tmp exec xp_cmdshell 'echo %windir%'SET @windir = (SELECT TOP 1 EnvVar from #Tmp)SELECT @windir as 'Windows Directory'

NOTE:To run this command, you need to be a member of the sysadmin fixed server. If you want others to be able to execute this command, you will have to explicitly grant them permission to execute the xp_cmdshell stored procedure.

Find more information about this stored procedure at MSDN.

See also  How HealthStream Learning Center Supports Healthcare Education and Compliance
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist