1

I want to create a user in the database. And I am using this stored procedure to create it:

CREATE PROCEDURE uspCreateUser
    @Name varchar(50)
AS
BEGIN 
   CREATE USER [@Name] 
   WITHOUT LOGIN WITH DEFAULT_SCHEMA=[dbo]    
END

But when I execute my stored procedure with

EXEC uspCreateUser 'anny'

this creates user with @Name in database.

Can you please tell me how can I fix this?

This screenshot can help you to understand the question

My database security folder -- User

1 Answer 1

2

You can use dynamic SQL. Generally, wherever the T-SQL syntax does not accept variable, dynamic SQL can provide the solution.

CREATE PROCEDURE uspCreateUser
    @Name varchar(50)
AS
BEGIN 
    DECLARE @sqlstr nvarchar(max) = 'CREATE USER '+ @Name 
        +' WITHOUT LOGIN WITH DEFAULT_SCHEMA=[dbo]'
    EXECUTE sp_executesql @sqlstr
END
GO

EXEC uspCreateUser 'anny';

You can find more information at:

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/62982480-e7b0-4729-87a7-c0c6f27c7f45/create-sql-user-with-username-password-parameters?forum=transactsql

http://www.sqlservercentral.com/Forums/Topic497615-359-1.aspx

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.