Wednesday, March 7, 2012

CREATE LOGIN problem

I know this is a really stupid question but I can't figure out how to make this work. It just doesn't seem to want variables. What is the proper syntax?

CREATE LOGIN [@.GUserName] FROM WINDOWS WITH DEFAULT_DATABASE=@.DBName, DEFAULT_LANGUAGE=[@.LoginLanguage]

You could put the command into a variable, and then execute the variable:

declare @.Command varchar(2000)

Select @.Command = 'CREATE LOGIN [' + @.GUserName + '] FROM WINDOWS WITH DEFAULT_DATABASE= ' + @.DBName + ' , DEFAULT_LANGUAGE=['+@.LoginLanguage +']'

exec (@.command)

BobP

|||

That didn't work...but this did....

declare @.tmp varchar(2000)

SET @.tmp = 'CREATE LOGIN [' + @.GUserName + '] FROM WINDOWS WITH DEFAULT_DATABASE= ' + @.DBName + ' , DEFAULT_LANGUAGE=['+@.LoginLanguage +']'

execute sp_executesql @.tmp

|||

Actually, this is the SET command that finally worked...

SET @.tmp = 'CREATE LOGIN ['+@.SQLLoginName+'] WITH PASSWORD = '''+@.Password+''', DEFAULT_DATABASE='+@.DBName+', DEFAULT_LANGUAGE='+@.LoginLanguage+''

|||

Actually, to make your code more robust, you should use:

SET @.tmp = 'CREATE LOGIN ' + quotename(@.SQLLoginName)
+ ' WITH PASSWORD = ' + quotename(@.Password, '''')
+ ', DEFAULT_DATABASE = ' + quotename(@.DBName)
+ ', DEFAULT_LANGUAGE= ' + quotename(@.LoginLanguage)

Otherwise, the code is open to injection. quotename will do the proper quoting and escaping, so you should always use it when building dynamic SQL commands.

Thanks
Laurentiu

No comments:

Post a Comment