Transact SQL – Get AD Domain Name

Background

Here I am reviewing code and noticing that it fails just about 100% of the time.

Nothing to be proud of.

 

Code

Original Code

Here is the original code


declare @regHKEY varchar(100);
declare @regPath varchar(100);
declare @regItem varchar(100);

DECLARE @strDomainName NVARCHAR(600); 

set @regHKEY = 'HKEY_LOCAL_MACHINE';  
set @regPath = 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon';
set @regItem = 'DefaultDomainName' ;
 
EXEC master.dbo.xp_regread 
          @regHKEY
        , @regPath 
        , @regItem
        , @strDomainName OUTPUT  
  
select [domain]	
		= @strDomainName

Output

Text


RegQueryValueEx() returned error 2, 'The system cannot find the file specified.'
Msg 22001, Level 1, State 1

 

Image

Troubleshooting

xp_regread appears to be failing due to permission issue; specifically the permission of the account running the SQL Server Engine.

 

Workaround

Here are some likely workaround:

  1. DEFAULT_DOMAIN
    • Undocumented function
  2. master..xp_loginconfig
    • Deprecated Extended Stored Procedure

 

Code

DEFAULT_DOMAIN


SELECT [domain] = DEFAULT_DOMAIN()

 

xp_loginconfig


exec master..xp_loginconfig 'default domain'

Summary

Nothing really to brag about.

Between undocumented & deprecated functions and unknown security requirements doing our best is a bit out of reach.

 

References

  1. xp_loginconfig (Transact-SQL)
    • Docs / SQL / Relational databases / System stored procedures
      xp_loginconfig
      Link

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s