I am a new in ms sql server and faced with the problem: i can’t drop a trigger in the database that is external to my current database.
So, I have 2 databases -CRM (main) and CrmHistory(where the history information is held).
In CrmHistory database I am writing some API to manage the gathering of the history information.
One of the task is to create\drop triggers in Crm database.
Here is my SP:
create procedure [dbo].[DropHistoryTriggers]
as
begin
set nocount on;
declare @sql table(s varchar(1000), id int identity)
declare @SqlStr nvarchar(max)=''
insert into @sql(s)
select 'drop trigger '+ name from Crm.sys.triggers
where name like '%History'
select @SqlStr=@SqlStr+s+' ' +char(13) from @sql
if (@SqlStr!='')
execute (@SqlStr)
end
While executing it, I get “Cannot drop the trigger ‘trndshistory’, because it does not exist or you do not have permission.”
Both databases is owned by ‘sa’.I create and execute SP also using ‘sa’ login.
How I tried to solve this issue:
- Set the TRUSTWORTHY property to ON on both databases.
- When I specified “with execute of owner\sa\self” I got the same error.
- I created another login, then create 2 users mapping to this login in both databases and granted AUTHENTICATE in the target database. Then I specified “execute as” in SP to impersonate this user.It doesn’t help me, to.
The problem is that you are pulling the triggers from a catalog view in the database crm, but then trying to drop them from the current database. To execute in the context of the other database, you can use:
As an aside, probably much easier to do this without a @table at all (uncomment the EXEC line when you are confident it is doing what it should):