T-SQL 语句以授予访问权限和创建帐户

T-SQL Statements to Grant Access and Create Account

如果我必须使用 T-SQL 授予对数据库的访问权限并验证用户是否已存在于 SQL 中, 如果用户不存在,则先创建帐户,然后授予对数据库的访问权限。

如果用户存在,只需授予对数据库的访问权限。

我只在 SQL 中创建用户。不在 Windows.

上面的内容将通过T-SQL查询来实现。 ?

首先尝试创建您的登录名,然后是您的用户。此代码首先检查您的所有用户分配到哪些数据库的位置。之后它检查是否创建了登录名,然后检查用户是否存在。它也是动态设置的,您只需输入一个 DBName。

例子

---Get information on which users has access to my datase
set nocount on
declare @permission table (
Database_Name sysname,
User_Role_Name sysname
)
declare @dbs table (dbname sysname)
declare @Next sysname
insert into @dbs
select name from sys.databases order by name
select top 1 @Next = dbname from @dbs
while (@@rowcount<>0)
begin
insert into @permission
exec('use [' + @Next + ']
SELECT ''' + @Next + ''', a.name as ''User or Role Name''
FROM [' + @Next + '].sys.database_principals a 
left join [' + @Next + '].sys.database_permissions d on a.principal_id = d.grantee_principal_id

order by a.name, d.class_desc')
delete @dbs where dbname = @Next
select top 1 @Next = dbname from @dbs
end
set nocount off


--Declare my Variables
Declare @DBName VARCHAR(30)
DECLARE @IsWindowsUser int = 0
DECLARE @UserName nvarchar(50) = 'hestt4545tt'
DECLARE @PassWord nvarchar(50) = 'hest123123'
DECLARE @LoginExists int
DECLARE @UserExists int

DECLARE @LoginSQL nvarchar(MAX)
DECLARE @UserSQL nvarchar(MAX)
DECLARE @MultiDatabase nvarchar(max) ='LegOgSpass,LoadConfiguration'
--SET @DBName = 'LegOgSpass'



DECLARE myCursor CURSOR FOR
select [value] from string_split(@MultiDatabase,',')

OPEN myCursor
FETCH NEXT  FROM myCursor INTO @DBName

WHILE @@FETCH_STATUS = 0
BEGIN
 exec('USE '+ @DBName)


IF @IsWindowsUser = 0
BEGIN
/* Users are typically mapped to logins, as OP's question implies, 
so make sure an appropriate login exists. */

SET @LoginExists = (Select count(principal_id) FROM sys.server_principals WHERE name = @UserName)

---Check if login exists - else create it
IF @LoginExists = 0
    BEGIN
         /* Syntax for SQL server login.  See BOL for domain logins, etc. */
        SET @LoginSQL = 'USE ' +@DBName + ' CREATE LOGIN '+@UserName +' WITH PASSWORD = '''+@PassWord+'''' 
        PRINT 'Login doesnt exists'
        EXEC (@LoginSQL)
        PRINT 'Therefore i make a new login now'

    SET @LoginExists = (Select count(principal_id) FROM sys.server_principals WHERE name = @UserName)
    IF @LoginExists = 1
    PRINT 'Login is now created and exists'
        BEGIN
        SET @UserExists = (SELECT count(principal_id) FROM sys.database_principals WHERE name = @UserName)
            IF @UserExists =0 
                PRINT 'User doesnt exists'
                BEGIN
                    SET @UserSQL = 'USE ' +@DBName+ ' CREATE USER ' +@UserName +' FOR LOGIN '+@UserName

                    EXEC (@UserSQL)
                    PRINT 'User is now created'
                END 
        END
    END
ELSE


    BEGIN
    SET @UserExists =  (select COUNT(distinct User_Role_Name) from @permission where User_Role_Name  =@UserName and Database_Name = @DBName)
            IF @UserExists =0 
            BEGIN
            PRINT 'Login already exists - go create user for access to database'
            SET @UserSQL = 'USE ' +@DBName+ ' CREATE USER ' +@UserName +' FOR LOGIN '+@UserName

            EXEC (@UserSQL)
            PRINT 'User is now created'
            END
    END

END
ELSE

BEGIN
SET @LoginExists = (Select count(principal_id) FROM sys.server_principals WHERE name = REPLACE(REPLACE(@UserName,'[',''),']',''))

---Check if login exists - else create it
IF @LoginExists = 0
    BEGIN
         /* Syntax for SQL server login.  See BOL for domain logins, etc. */
        SET @LoginSQL = 'USE ' +@DBName + ' CREATE LOGIN '+@UserName +' FROM WINDOWS' 
        PRINT 'Windows Login doesnt exists'
        EXEC (@LoginSQL)
        PRINT 'Therefore i make a new window login now'

    SET @LoginExists = (Select count(principal_id) FROM sys.server_principals WHERE name = @UserName)
    IF @LoginExists = 1
    PRINT 'Windows Login is now created and exists'
        BEGIN
        SET @UserExists = (SELECT count(principal_id) FROM sys.database_principals WHERE name = @UserName)
            IF @UserExists =0 
                PRINT 'User doesnt exists'
                BEGIN
                    SET @UserSQL = 'USE ' +@DBName+ ' CREATE USER ' +@UserName +' FOR LOGIN '+@UserName

                    EXEC (@UserSQL)
                    PRINT 'User is now created'
                END 
        END
    END
ELSE



    BEGIN
    SET @UserExists =  (select COUNT(distinct User_Role_Name) from @permission where User_Role_Name  =REPLACE(REPLACE(@UserName,'[',''),']','') and Database_Name = @DBName)
            IF @UserExists =0 
            BEGIN
            PRINT 'Window Login already exists - go create user for access to database'
            SET @UserSQL = 'USE ' +@DBName+ ' CREATE USER ' +@UserName +' FOR LOGIN '+@UserName

            EXEC (@UserSQL)
            PRINT 'User is now created'
            END
    END

END
FETCH NEXT FROM myCursor INTO @DBName
--Ending cursor
END
CLOSE myCursor
DEALLOCATE myCursor