9

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

This is to run on SQL Server 2005.

4

6 回答 6

5

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.

于 2009-10-27T17:43:27.707 回答
3

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.

于 2009-05-13T04:37:11.987 回答
3

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

于 2009-09-10T14:57:05.320 回答
2

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.

于 2009-05-13T05:04:56.700 回答
2

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.

于 2009-05-13T05:13:10.400 回答
2

To determine a specific environment variable in T-SQL (MS SQL Server) you can do something like:

Grant Security Permissions

use [master]

execute sp_configure 'show advanced options', 1
reconfigure
go

execute sp_configure 'xp_cmdshell', 1
reconfigure
go

grant execute on xp_cmdshell to [DOMAIN\UserName]

grant control server to [DOMAIN\UserName]
go

Source: https://stackoverflow.com/a/13605864/601990

Use Environment Variables

-- name of the variable 
declare @variableName nvarchar(50) = N'ASPNETCORE_ENVIRONMENT'

-- declare variables to store the result 
declare @environment nvarchar(50)
declare @table table (value nvarchar(50))

-- get the environment variables by executing a command on the command shell
declare @command nvarchar(60) = N'echo %' + @variableName + N'%';
insert into @table exec master..xp_cmdshell @command;
set @environment = (select top 1 value from @table);

-- do something with the result 
if @environment = N'Development' OR @environment = N'Staging'
    begin
    select N'test code'
    end
else 
    begin
    select N'prod code'
    end

Also remember to restart the SQL Server Service when changing the Environment Variables.

于 2018-09-10T15:11:17.357 回答