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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With