I am trying to remove/ drop a users permissions but i keep getting the following error:
The server principal “DevMe” is not able to access the database
“CallManager” under the current security context.
My Stored proc to do this looks as follows:
USE [AuditIT]
GO
/****** Object: StoredProcedure [dbo].[AdminDevUserDelete] Script Date: 06/29/2012 08:54:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--alter table AdminLog add HostName varchar(128) NULL DEFAULT HOST_NAME()
ALTER PROCEDURE [dbo].[AdminDevUserDelete]
@SQLLoginName varchar(50)
AS
DECLARE @DatabaseName varchar(1000)
PRINT 'USE [master] DROP LOGIN [' + @SQLLoginName + ']'
EXEC ('USE [master] DROP LOGIN [' + @SQLLoginName + ']')
DECLARE CSDatabase CURSOR FOR
SELECT
[Name]
FROM
[Master]..SysDatabases
--WHERE
-- --[sid] = 0x01
-- [Name] NOT IN ('ReportSRV.Support','HelpDeskFacilities','QuestSoftware')
ORDER BY
dbid DESC
OPEN CSDatabase
FETCH NEXT FROM CSDatabase INTO @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ('SELECT [Name] FROM [' + @DatabaseName + ']..SysUsers WHERE [Name] = ''' + @SQLLoginName + '''')
IF @@RowCount > 0
BEGIN
PRINT 'USE [' + @DatabaseName + '] DROP USER [' + @SQLLoginName +']'
EXEC ('USE [' + @DatabaseName + '] DROP USER [' + @SQLLoginName +']')
END
FETCH NEXT FROM CSDatabase INTO @DatabaseName
END
CLOSE CSDatabase
DEALLOCATE CSDatabase
Could someone please explain how i could fix this problem?
]character. Same goes for'quotes, use QUOTENAME again (it can quote both[and', see the linked spec). Your code will break on names that contain embeded'.DROP USERthen use the appropiate catalog views:sys.database_principalsandsys.databases.Finaly, what is the problem causing the error you see? Is in the code you did not post, namely how you call this stored procedure. The error indicates that you are in EXECUTE AS sandbox mode, see Understanding Execution Context and Understanding Context Switching. You need to properly code sign your procedure so that it can extend the context to the server level (since you’re touching arbitrary database, cross database code signing won’t be enough).
BTW if you’re not under eXECUTE AS context then is plain and simply you don’t have access to the database in question, so it’s a mute question since you do not have the rights to do what you’re trying to do. The other points still remain, and the proper wait to get the needed right for this procedure is still to use code signing, given what is trying to do…
Update:
Your C# code is also SQL injection prone… this is really a turkey shoot. Don’t build your procedure name by
procedure = dataBase + ".." + procedure!!