tags:

views:

1353

answers:

2

I want to write a SQL 2005 script to create a new login that uses Windows authentication. The Windows user is a local account (not a domain one). A local account with the same name exists on many SQL Server machines and I want to run the same script on all of them.

It seemed simple enough:

CREATE LOGIN [MyUser]
FROM WINDOWS

However, that doesn't work! SQL returns an error, saying Give the complete name: <domain\username>.

Of course, I can do that for one machine and it works, but the same script will not work on other machines.

+1  A: 

This just worked for me:

DECLARE @sql nvarchar(1000)
SET @SQL = 'CREATE LOGIN [' + @@SERVERNAME + '\MyUser] FROM WINDOWS'
EXEC sp_executeSQL @SQL
beach
+1  A: 

Looks like sp_executesql is the answer, as beach posted. I'll post mine as well, because @@SERVERNAME doesn't work correctly if you use named SQL instances, as we do.

DECLARE @loginName SYSNAME
SET @loginName = CAST(SERVERPROPERTY('MachineName') AS SYSNAME) + '\MyUser'

IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE [name] = @loginName)
BEGIN
    DECLARE @sql NVARCHAR(1000)
    SET @sql = 'CREATE LOGIN [' + @loginName + '] FROM WINDOWS'
    EXEC sp_executesql @sql
END
Evgeny