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
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.
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 []
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 []
USE []
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE
[name] = N'' and Type = 'R')
CREATE ROLE []
USE []
EXEC sp_addrolemember N'', N''
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