September 29, 2010

Read Environment Variables in T-SQL




I had recently posted on Use xp_cmdshell results in T_SQL. One of the blog readers Andrew got back asking if it was possible to read Environment Variables using this method and store the value in a variable for later use.

Here’s the query. The variable @windir holds the value and you can use it as you want: (Thanks to my colleague Karthi for simplying the query further)

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'
-- DROP TABLE #Tmp

Note: Observe I am using ‘TOP 1’ in the query since the subquery returned more than one row, one of them being a blank row. I am not sure why is the blank row returned and till I find it out, I will stick with the ‘TOP 1’ command.

OUTPUT

image


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Read Environment Variables in T-SQL"
  1. Bharani said...
    October 4, 2010 at 12:09 AM

    when we execute this command "exec xp_cmdshell 'echo %windir%' " in cmd prompt we get a blank line. this blank line is been taken as NULL i believe.

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions