I've written the following stored procedure:
CREATE PROCEDURE dbo.usp_DEMO
@LOGINSQL VARCHAR(30),
@DBNAME VARCHAR(40)
WITH EXECUTE AS owner
AS
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'USE'
SET @SQL = @SQL + ' ' + @DBNAME + ' ' + ' CREATE USER ' + ' '
+ @LOGINSQL + ' ' + ' FOR LOGIN ' + ' ' + @LOGINSQL + ' '
+ ' ALTER ROLE [DB_OWNER] ADD MEMBER ' + ' '
+ @LOGINSQL
EXEC sp_executesql @SQL
Running like this:
use master
go
exec usp_DEMO '<LOGIN>','<DATABASE>'
I'm running from Master
in a SQL Server 2019 STD Edition (RTM-CU6) (KB4563110) and I get this error:
Msg 916, Level 14, State 2, Line 14
The server principal "<OWNER_LOGIN>" is not able to access the database "<DB_NAME>" under the current security context.
The idea is using a stored procedure to map a login to database and give db_owner
role.
Any idea how can I solve the error?