Create Login from master

  • Is there any way I can create a login for a database while the database context is master or not the particular database.

    Actually, the database will be known during runtime, and a login needs to be created.

    Chandrachurh Ghosh
    DBA – MS SQL Server
    Ericsson India Global Services Limited
    Quality is not an act, it is a habit.

  • You maps a login or a user to a particular database only after creating the user.

  • That is true. I am already able to create the login, but cannot grant connect to the database....It says the login is not available or you do not have permission...

    ----------------------CREATE LOGIN-----------------------------------------------

    declare @SQL_DBvarchar(20),

    @STRSQL1varchar(500),

    @STRSQL2varchar(500),

    @STRSQL3varchar(500),

    @STRSQL4varchar(500)

    SET @SQL_DB='USE '+@DATABASE_NAME

    SET @STRSQL1=(' IF NOT EXISTS (SELECT *

    FROM sys.server_principals

    WHERE name='''+@DB_USER+''')')

    SET @STRSQL2=(' BEGIN

    CREATE LOGIN '+@DB_USER+'

    WITH PASSWORD=N'''+@DB_USER+''',

    DEFAULT_DATABASE=['+@DATABASE_NAME+'],

    DEFAULT_LANGUAGE=[us_english],

    CHECK_EXPIRATION=OFF,

    CHECK_POLICY=OFF

    END')

    SET @STRSQL3=(' EXEC sys.sp_addsrvrolemember @loginame = N'''+@DB_USER+''', @rolename = N''sysadmin''')

    SET @STRSQL4=(' ALTER LOGIN ['+@DB_USER+'] DISABLE')

    EXEC (@SQL_DB+@STRSQL1+@STRSQL2+@STRSQL3+@STRSQL4)

    ------------------------CREATE USER----------------------------------------------

    SET @STRSQL1=(' IF NOT EXISTS (SELECT *

    FROM '+@DATABASE_NAME+'.sys.server_principals

    WHERE name='''+@DB_USER+''')')

    SET @STRSQL2=(' CREATE USER ['+@DB_USER+']

    FOR LOGIN ['+@DB_USER+']

    WITH DEFAULT_SCHEMA=[dbo]')

    EXEC (@SQL_DB+@STRSQL1+@STRSQL2+@STRSQL3)

    SET @STRSQL1=(' GRANT CONNECT TO ['+@DB_USER+']')

    EXEC (@SQL_DB+@STRSQL1)

    Chandrachurh Ghosh
    DBA – MS SQL Server
    Ericsson India Global Services Limited
    Quality is not an act, it is a habit.

  • According to BOL, the CREATE USER statement is "Requires ALTER ANY USER permission on the database." This will be in addition to having EXECUTE permission on your stored procedure in the database where this code resides and/or is executed. You need to check the permissions required in the database to GRANT CONNECTION and anything else being done within the database. E.g., GRANT EXECUTE minimally requires having CONTROL permission on that object.

    David Lathrop
    DBA
    WA Dept of Health

  • Is this a single login or is the application creating logins at runtime too.. Pl describe how the logins/users are created vias the application.

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

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