Help with Login Script

  • Hello:

    I am new to SQL Server and I am trying to create a script / possible a cursor that will allow me to create multiple logins in one pass - without having to type each one.

    I have 20 users USER1, USER2, USER3, USER4... but I can't seem to figure out how to get those users into a loop

    so I can end up with something like this.

    CREATE LOGIN <user> FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[English]......

    I realize I can type this statement 20 times but perhaps there is a faster way -

    Any help greatly appreciated.

    Thank you

    Terry

  • What about this:-

    CREATE TABLE dbo.UserNames

    (UserID INT IDENTITY(1,1) PRIMARY KEY,

    UserName SYSNAME);

    INSERT INTO dbo.UserNames

    SELECT 'User1'

    UNION

    SELECT 'User2'

    --etc

    SELECT 'CREATE LOGIN ' + UserName + ' FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[English]'

    FROM dbo.UserNames

    It's a bit of effort to get setup but should allow you to generate the statement all at once quickly.

  • Before I provide a script, I have a question:

    Are all these Logins going to have the same access to the server and database?

    If they are you should create an active directory group for them and just create one login on the SQL Server for the group.

    Here's a fairly simple script that generates the CREATE LOGIN:

    DECLARE @counter TINYINT = 1

    DECLARE @sql NVARCHAR(500) = N'CREATE LOGIN user<N> FROM WINDOWS'

    WHILE @counter <=20

    BEGIN;

    DECLARE @newSQL NVARCHAR(500) = REPLACE(@sql, '<N>', CONVERT(NVARCHAR(2), @counter));

    PRINT @newSQL;

    --EXEC (@newSQL);

    SET @counter += 1;

    END;

    Notice the EXEC is commented out because I don't have those users in my domain.

  • Wow!

    Thank you Jack.

    This is great -

    No AD in this case (one of those rare situations).

    These are logins unique to each server - same login names across the board, but

    different servers.

    But this will work nicely.

    thanks again.

    have a great day!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply