• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 502
  • Last Modified:

SET IDENTITY_INSERT ON

Hello
for some sync reasons ... i've create a trigger for Insert on a specific table and i need  need to insert the same data in other database
the problem is sql server not allow to use
 SET IDENTITY_INSERT ON  to refer a tble in other database

how i can do that
0
ali_alannah
Asked:
ali_alannah
1 Solution
 
Surendra NathCommented:
create a stored procedure, in the other database of yours and put the set identity insert on in the stored proc.

Now create a temp table with the same schema as the target table and insert the data into the temp table in the trigger.

Use the same temp table to populate the target table from the stored proc.
As temporary tables can be accessed acorss the databases, they will have the same data as long as it is the same server and the same SPID.

The below code is just a sample, this wont compile 100% in your system, it is just for assisting you.
Example code

[b]trigger[/b]

create trigger trg_abcd 
AS
BEGIN

create table #abcd
(
 a int
, b int
, c int
)

insert into #abcd select * from deleted -- (or inserted)

exec <anotherDatabase>.dbo.usp_abcd
END

[b]Stored procedure[/b]

create procedure usp_abcd
AS
BEGIN
SET IDENTITY_INSERT ON
insert into <target Table>
select * from #abcd
END

Open in new window

0
 
Anthony PerkinsCommented:
Unrelated to your problem and in case you were not aware SET IDENTITY_INSERT requires the following permissions:
User must own the object, or be a member of the sysadmin fixed server role, or the db_owner and db_ddladmin fixed database roles.
This requirement, in most shops, disqualifies its use in any user code.
0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Tackle projects and never again get stuck behind a technical roadblock.
Join Now