在T-SQL中使用环境变量

问题描述 投票:3回答:6

如何在T-SQL脚本中读取系统环境变量的值?

这是在SQL Server 2005上运行。

sql sql-server-2005 environment-variables
6个回答
2
投票

这应该给你一个列表(假设你允许人们执行xp_cmdshell)

exec master..xp_cmdshell'set'

注意:xp_cmdshell存在安全隐患......

您还可以使用托管存储过程扩展存储过程或通过com组件执行此操作。


2
投票

出于安全原因,通常最好避免使用xp_cmdshell。

你最好使用CLR程序集。这是对creating a CLR assembly的一个很好的介绍。

你可以在C#中使用System.Environment.GetEnvironmentVariable() - 你会找到更多关于如何做here的信息。


2
投票

谢谢你的回答。他们帮助我找到了一个有效的解决方案,尽管这可能不是最先进的方法:

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

具体来说,我试图获取主机名,echo%computername%可以用hostname系统命令替换。但这适用于任何环境变量。


2
投票

嘿,如果你想获得服务器名称,只需调用SELECT @@SERVERNAME


2
投票

要“读取T-SQL脚本中的系统环境变量的值”,可以将SQL Management Studio设置为使用“sqlcmd模式”。

然后你可以像这样使用:

Print '$(TEMP)'

:r $(Temp)\Member.sql
go

我不确定这是如何在“SQL Management Studio”之外完成的,但它应该很难找到。


1
投票

要在T-SQL(MS SQL Server)中确定特定的环境变量,您可以执行以下操作:

授予安全权限

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

资料来源:https://stackoverflow.com/a/13605864/601990

使用环境变量

-- 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

还记得在更改环境变量时重新启动SQL Server服务。

© www.soinside.com 2019 - 2024. All rights reserved.