views:

2554

answers:

5

How can I read the value of a system environment variable in a T-SQL script?

This is to run on SQL Server 2005.

+1  A: 

This should give you a list (provided you allow people to execute xp_cmdshell)

exec master..xp_cmdshell 'set'

Note: xp_cmdshell is a security hazard ...

You could also do this with a managed stored proc an extended stored proc or via a com component.

Sam Saffron
+2  A: 

xp_cmdshell is generally best avoided for security reasons.

You're better off using a CLR assembly. Here's a good introduction to creating a CLR assembly.

You can use System.Environment.GetEnvironmentVariable() in C# - you'll find more info on how to do that here.

Aaron Alton
I agree about xp_cmdshell but since it is already enabled I can use it in this instance
benPearce
the undocumented proc xp_regread could also probably be used by reading the registry
SQLMenace
A: 

Thanks for the answers. They helped me get to a working solution, although this is probably not the most advanced method:

declare @val varchar(50)
create table #tbl (h varchar(50))
insert into #tbl exec master..xp_cmdshell 'echo %computername%'
set @val = (select top 1 h from #tbl)
drop table #tbl

Specifically I was trying to get the hostname, the echo %computername% could be replaced with the hostname system command. But this now works for any environment variable.

benPearce
Does that return something different than "select \@\@servername"?
Ron Savage
+1  A: 

Hey, if you want to get the server name, just call SELECT @@SERVERNAME

Rodrigo
+1  A: 

To "read the value of a system environment variable in a T-SQL script" you can set SQL Management Studio to use "sqlcmd Mode".

Then you can use like this:

Print '$(TEMP)'

:r $(Temp)\Member.sql
go

I'm not sure how this is done outside of "SQL Management Studio" but it should be hard to find out.

RE: One way it's done outside sql management studio is to use sqlcmd.exe (it runs in sqlcmd mode by default)
Jason Jarrett