views:

487

answers:

3

I'm a developer and I suck at SQL:) Please help me out here.

I'd like to create my own Stored Procedure that creates a Tenant in my SaaS database. In order to do this I need to create a new SQL Login for the Tenant and then add it to a predefined SQL Role.

I'm already stumped just trying to create the Login. Here is what I've tried...

CREATE PROCEDURE [MyScheme].[Tenants_InsertTenant] @username nvarchar(2048), @password nvarchar(2048)

AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

CREATE LOGIN @username WITH PASSWORD = @password

END

Msg 102, Level 15, State 1, Procedure Tenants_InsertTenant, Line 16 Incorrect syntax near '@username'. Msg 319, Level 15, State 1, Procedure Tenants_InsertTenant, Line 16 Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

I realize this should be straightforward but when your new to SQL and the SQL manager errors are as cryptic as they seem to be to me its better just to ask for help:)

Thanks, Justin

+2  A: 

Apparently CREATE LOGIN only accepts literals. You could try wrapping it in an exec and building it as a string:

EXEC('CREATE LOGIN ' + quotename(@username) + ' WITH PASSWORD = ' + quotename(@password))

edit: added quotename for safety from sql injection attacks

codeulike
Thanks for the fast response. That appears to work. Is it better than usingEXEC sp_addlogin @username, @passwordFrom what I've read sp_addlogin is deprecated.
Justin
I don't know if its better than sp_addlogin, but you're right that sp_addlogin is deprecated. From the conversation [here](http://social.msdn.microsoft.com/Forums/en-US/sqlsecurity/thread/ad63208a-48d1-4307-9275-5bf20a6386a5) it appears Exec() is the only official way until microsoft get round to parameterizing the CREATE LOGIN command.
codeulike
A: 

Try this:

declare @t nvarchar(4000)
set @t = N'CREATE LOGIN ''''' + @username + ''''' WITH PASSWORD = ''''' + @password
exec sys.sp_executesql @t
eKek0
A: 

Posible solution:

sp_addlogin @loginame = 'test', @passwd = 'test', @defdb = 'test'

Galkin
This works as well. If only I could mark two as answers.
Justin