Checking if a SQL Server login already exists

前端 未结 10 2109
盖世英雄少女心
盖世英雄少女心 2020-12-12 12:27

I need to check if a specific login already exists on the SQL Server, and if it doesn\'t, then I need to add it.

I have found the following code to actually add the

10条回答
  •  青春惊慌失措
    2020-12-12 12:36

    In order to hande naming conflict between logins, roles, users etc. you should check the type column according to Microsoft sys.database_principals documentation

    In order to handle special chacters in usernames etc, use N'' and [] accordingly.

    Create login

    USE MASTER
    IF NOT EXISTS (SELECT 1 FROM master.sys.server_principals WHERE 
    [name] = N'' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
        CREATE LOGIN [] 
    

    Create database user

    USE []
    IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE 
    [name] = N'' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
        CREATE USER [] FOR LOGIN []
    

    Create database role

    USE []
    IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE 
    [name] = N'' and Type = 'R')
        CREATE ROLE []
    

    Add user to role

    USE []
    EXEC sp_addrolemember N'', N''
    

    Grant rights to role

    USE []
    GRANT SELECT ON [] TO []
    GRANT UPDATE ON [] ([]) TO []
    GRANT EXECUTE ON [] TO []
    

    The SQL is tested on SQL Server 2005, 2008, 2008 R2, 2014, 2016, 2017, 2019

提交回复
热议问题