Using Environment variables in T-SQL

前端 未结 6 1877
独厮守ぢ
独厮守ぢ 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:14

    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.

提交回复
热议问题