Checking if a SQL Server login already exists

前端 未结 10 2107
盖世英雄少女心
盖世英雄少女心 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条回答
  •  萌比男神i
    2020-12-12 12:38

    First you have to check login existence using syslogins view:

    IF NOT EXISTS 
        (SELECT name  
         FROM master.sys.server_principals
         WHERE name = 'YourLoginName')
    BEGIN
        CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
    END
    

    Then you have to check your database existence:

    USE your_dbname
    
    IF NOT EXISTS
        (SELECT name
         FROM sys.database_principals
         WHERE name = 'your_dbname')
    BEGIN
        CREATE USER [your_dbname] FOR LOGIN [YourLoginName] 
    END
    

提交回复
热议问题