Monday, March 15, 2010

create sql users from a table

If you want to create Sql Server database users from an table (TABLE_USERS) you can use this code:

DECLARE @name VARCHAR(100)
DECLARE @cnp VARCHAR(100)
DECLARE @userName VARCHAR(100)
DECLARE @sql NVARCHAR(300)
DECLARE @id int
DECLARE @Name varchar(100)

DECLARE db_cursor CURSOR FOR
select   a.DomainName, c.Code,c.Name from TABLE_USERS

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name,@cnp ,@Name
WHILE @@FETCH_STATUS = 0
BEGIN

SET @userName = ltrim(rtrim(@name))
IF not EXISTS (SELECT * FROM sys.server_principals WHERE name = @userName)
begin
     select @sql = 'CREATE LOGIN ['+@userName+'] FROM WINDOWS  
           WITH  DEFAULT_DATABASE = [DATABASE],  DEFAULT_LANGUAGE=[us_english]'

     EXEC sp_executesql @sql
 
    select @sql = 'CREATE USER ['+@userName+'] FOR LOGIN ['+@userName+'] WITH  
          DEFAULT_SCHEMA=[dbo]'
    EXEC sp_executesql @sql
end

select @sqlRollMember = 'execute sp_addrolemember '+@DBRole2+' , '''+@userName + ''''
EXEC sp_executesql @sqlRollMember
END
CLOSE db_cursor
DEALLOCATE db_cursor

No comments:

Post a Comment