[英]Using Environment variables in T-SQL
如何在T-SQL腳本中讀取系統環境變量的值?
這是在SQL Server 2005上運行。
要“讀取T-SQL腳本中的系統環境變量的值”,可以將SQL Management Studio設置為使用“sqlcmd模式”。
然后你可以像這樣使用:
Print '$(TEMP)'
:r $(Temp)\Member.sql
go
我不確定這是如何在“SQL Management Studio”之外完成的,但它應該很難找到。
嘿,如果你想獲得服務器名稱,只需調用SELECT @@SERVERNAME
這應該給你一個列表(假設你允許人們執行xp_cmdshell)
exec master..xp_cmdshell'set'
注意:xp_cmdshell存在安全隱患......
您還可以使用托管存儲過程擴展存儲過程或通過com組件執行此操作。
謝謝你的回答。 他們幫助我找到了一個有效的解決方案,盡管這可能不是最先進的方法:
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系統命令替換。 但這適用於任何環境變量。
要在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服務 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.