问题
I need to grant the user access to a database from inside a stored procedure in SQL Server, but when I try to use this code, the DB in use does not change and when I run the code without using EXEC
, I get an error:
USE database statement is not allowed in a procedure
My code:
CREATE PROCEDURE [dbo].[usp_AddUserDBToTables]
(@UserGroup NCHAR(30), -- DBdetail, DBxref
@DBName NCHAR(30)) -- DBdetail, DBxref
AS
BEGIN
DECLARE @sqlcmd NVARCHAR(1024);
-- Add the UserGroup to the new UserDB
SET @sqlcmd = 'USE [' + rtrim(ltrim(@DBName)) + ']'
PRINT (@sqlcmd)
EXEC (@sqlcmd)
PRINT 'now using ' + db_name()
SET @sqlcmd = 'CREATE USER [' + rtrim(ltrim(@UserGroup)) + '] FOR LOGIN [' + rtrim(ltrim(@UserGroup)) + ']'
PRINT (@sqlcmd)
EXEC (@sqlcmd)
SET @sqlcmd = 'ALTER ROLE [db_owner] ADD MEMBER [' + rtrim(ltrim(@UserGroup)) + ']'
PRINT (@sqlcmd)
EXEC (@sqlcmd)
SET @sqlcmd = 'USE [HOSTED_SUPPORT]'
PRINT (@sqlcmd)
EXEC (@sqlcmd)
END
The user group is added to HOSTED_SUPPORT, not @DBName. Print statements generated this, but I received no errors when using dynamic SQL:
USE [ZU_1077a]
now usingZMIT_HOSTED_SUPPORT
CREATE USER [ZMCLIENT\1007 FirstBank] FOR LOGIN [ZMCLIENT\1007 FirstBank]
ALTER ROLE [db_owner] ADD MEMBER [ZMCLIENT\1007 FirstBank]
USE [ZMIT_HOSTED_SUPPORT]
How can I make this work from inside a stored procedure?
回答1:
You need to put all the command in one dynamic SQL and run it because the USE DATABASE will be out of when the first dynamic SQL containing the USE command is executed.
So, remove all the EXEC except the last one, and concat all the SQL in @sqlcmd. Run EXEC the @sqlcmd.
来源:https://stackoverflow.com/questions/60062977/how-to-grant-user-access-to-a-db-from-inside-a-stored-procedure-in-sql-server-g