sql - Cursor which create user and assign role -


i have list of users requer on server used domain autentification, have temp table in ian loading users cab file. need create users based on records in temp file

how cursor create records?

i trying

declare cursor1 cursor select * #temp;  open cursor1  fetch next cursor1 @userprofile  while @@fetch_status = 0 begin     create user @userprofile     login @userprofile go      exec sp_addrolemember 'role'         ,@userprofile      fetch next     cursor1     @userprofile end  close cursor1  deallocate cursor1 

however it's throwing me error

msg 102 incorrect syntax near @userprofile , msg 137 must declare scalar variable @userprofile 

you cannot use variables inline object names calls commands such create user. need , use dynamic sql instead:

edit - use sp_adduser instead of dynamic sql in example. however, stored procedure has been deprecated of sql server 2012. therefore, if using version of above, stick dynamic sql , create user command.

dynamic sql if sql2012 or greater

declare @userprofile varchar(20)  declare cursor1 cursor             select             *         #temp; open cursor1 fetch next cursor1 @userprofile while @@fetch_status = 0 begin     declare @sql varchar(max)      set @sql = 'create user ' + @userprofile + ' login ' + @userprofile      --print @sql     exec (@sql)      exec sp_addrolemember   'role'                             ,@userprofile      fetch next cursor1 @userprofile end close cursor1 deallocate cursor1 

sp_adduser if prior:

exec sys.sp_adduser @loginame = @userprofile                         ,@name_in_db = @userprofile 

i have commented out print statement. however, if uncomment it. can see commands it's creating cursor.


Comments