Using Environment variables in T-SQL

前端 未结 6 1879
独厮守ぢ
独厮守ぢ 2021-01-18 16:31

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

This is to run on SQL Server 2005.

6条回答
  •  一个人的身影
    2021-01-18 17:17

    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.

提交回复
热议问题