代码之家  ›  专栏  ›  技术社区  ›  benPearce

在T-SQL中使用环境变量

  •  3
  • benPearce  · 技术社区  · 17 年前

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

    这将在SQLServer2005上运行。

    6 回复  |  直到 17 年前
        1
  •  5
  •   user197525    16 年前

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

    然后您可以这样使用:

    Print '$(TEMP)'
    
    :r $(Temp)\Member.sql
    go
    

        2
  •  3
  •   Sam Saffron James Allen    17 年前

    注意:xp_cmdshell是一种安全隐患。。。

    您还可以使用托管存储过程、扩展存储过程或通过com组件来实现这一点。

        3
  •  2
  •   Aaron Alton    17 年前

    最好使用CLR程序集。这里有一个很好的介绍 creating a CLR assembly .

    您可以在C#中使用System.Environment.GetEnvironmentVariable()——您将找到有关如何执行此操作的更多信息 here .

        4
  •  2
  •   benPearce    17 年前

    谢谢你的回答。

    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
    

    主机名 系统命令。但这现在适用于任何环境变量。

        5
  •  2
  •   Rodrigo    16 年前

    嘿,如果你想知道服务器名,只要打电话 SELECT @@SERVERNAME

        6
  •  2
  •   MovGP0    7 年前

    要确定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服务 更改环境变量时。