Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create users dynamic names and assgin roles

I need to create user with dynamic names with a variable name

example :

The following code gives a syntax error.

Create Login @User_name WITH PASSWORD @password;
                USE database; 

and i need to assign a role for created user ..

like image 930
Sudantha Avatar asked Feb 14 '11 11:02

Sudantha


2 Answers

You can not use create login with variables. You have to create the statement dynamically or you can use sp_addlogin. According to http://msdn.microsoft.com/en-us/library/ms173768.aspx sp_addlogin is deprecated.

declare @UN sysname
declare @PW sysname
declare @S nvarchar(100)

set @UN = 'UserName'
set @PW = 'Password'

set @S = 'CREATE LOGIN ' + quotename(@UN) + ' WITH PASSWORD = ' + quotename(@PW, '''')

exec (@S)
like image 134
Mikael Eriksson Avatar answered Oct 10 '22 21:10

Mikael Eriksson


You cannot use variables for object names. You can cheat

exec sp_addlogin @User_name, @password;

Either that or construct dynamic SQL, but make sure to use QUOTENAME to prevent SQL injection.

like image 42
RichardTheKiwi Avatar answered Oct 10 '22 20:10

RichardTheKiwi