Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL CREATE LOGON - can't use @parameter as username

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

like image 961
Justin Avatar asked May 07 '09 22:05

Justin


1 Answers

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

like image 105
codeulike Avatar answered Sep 23 '22 22:09

codeulike