Solved

Simple SQL Insert Trigger

Posted on 2014-11-10
15
147 Views
Last Modified: 2014-11-14
I have  a database with account numbers in it.

I wan to create a trigger that upon insert of that table it sends all those accounts numbers to another db on the same server.

Then I want the new DB to have a trigger on it that adds feilds to another table in the same DB when inserted using the account number that has come in.

For instance

DB - A table B  gets account number 1234 inserted into it.

Trigger runs and inserts 1234 into DB - B - Table A

Trigger on DB B sees it has an insert and then runs an insert statement on table forms in DB B . Using the account 1234.
0
Comment
Question by:desiredforsome
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 2
15 Comments
 
LVL 50

Expert Comment

by:Vitor Montalvão
ID: 40434491
So, what kind of help you need from us?

If the DB's are in the same instance you just need to give the full reference to the objects (DB.Schema.Object):
INSERT INTO dbB.dbo.tableA
FROM inserted

Open in new window


If there's no transformations or any other operations than simple inserts you can use a transactional replication instead of the triggers.
0
 
LVL 40

Expert Comment

by:lcohan
ID: 40436169
"I wan to create a trigger that upon insert of that table it sends all those accounts numbers to another db on the same server."

I believe it is wrong to rely on the SQL Database backend to populate multiple tables with data inserted into a single table and in my opinion (and hopefully many others) your UI / APP should INSERT/DELETE/UPDATE all necessary tables with the data as it should be stored in the database and not to rely on hidden SQL objects to do that for you. All you need is the appropriate connections and statements for this to work.

http://programmers.stackexchange.com/questions/171024/never-do-in-code-what-you-can-get-the-sql-server-to-do-well-for-you-is-this
0
 
LVL 50

Expert Comment

by:Vitor Montalvão
ID: 40436787
I believe it is wrong to rely on the SQL Database backend to populate multiple tables with data inserted into a single table and in my opinion (and hopefully many others) your UI / APP should INSERT/DELETE/UPDATE all necessary tables with the data as it should be stored in the database and not to rely on hidden SQL objects to do that for you.
Sorry but I can't agree with you. Business model should always kept in the databases and a trigger isn't an hidden SQL object. It's more easy to change a trigger or stored procedure than an application code. Also, let the servers do the heaviest work and not the clients.
0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Comment

by:desiredforsome
ID: 40437406
I am new at writing triggers so A good example would be appreciated. The reason I cannot do this from the UI. is becuase I am writing an interface to the software and the software is 3rd party in which I cannot access anything to code to sql other than creating a trigger in the db itself.

My interface has its own DB it relies on but needs some data populated into it from the 3rd party db.

THe instance is the same its runnning on a sql express.

Just need the account number that was inserted in to be inserted into my db from 3rd party.

THank You
0
 
LVL 40

Expert Comment

by:lcohan
ID: 40437440
Your trigger would be something like in the pseudo code below:

CREATE TRIGGER [TI_TableB] ON  DB_A.[dbo].[TableB]
   AFTER INSERT
AS
BEGIN

-- stop the recursive trigger from firing more than once ... comment it out if you have bulk insert
IF ((SELECT TRIGGER_NESTLEVEL()) > 1 )
BEGIN
   RETURN
END


IF EXISTS (SELECT account_number FROM inserted)
INSERT INTO DB_B.[dbo].[TableA] (account_number, 'rest of the columns here from the table definition',...)
   SELECT   account_number, 'rest of the columns here from the table definition',...
      FROM inserted

END

GO
0
 

Author Comment

by:desiredforsome
ID: 40437846
Would "inserted" by DB-A or DB-B?
0
 

Author Comment

by:desiredforsome
ID: 40437851
SEem to be getting error saying that xrefid is not permitted in this context.

Please tell me if this trigger looks ok of if it has issues and what they may be.

CREATE TRIGGER INSERTTABLEPORTAL ON  outlookreport.dbo.MFUSERS
   AFTER INSERT 
AS 
BEGIN

-- stop the recursive trigger from firing more than once ... comment it out if you have bulk insert
IF ((SELECT TRIGGER_NESTLEVEL()) > 1 )
BEGIN
   RETURN
END


IF EXISTS (SELECT xrefid FROM outlookreport.dbo.requestdoc)
INSERT INTO outlookreport.dbo.requestdoc values(xrefid,'test','Y','N')
   SELECT   xrefid,requested,status,required
      FROM outlookreport.dbo.requestdoc

END

GO

Open in new window

0
 

Author Comment

by:desiredforsome
ID: 40442633
I have got the trigger to work kind of. It however is inserted it everytime. It does not just insert if not exists. I want it to only insert the inserted data if it does not exists.
0
 
LVL 50

Expert Comment

by:Vitor Montalvão
ID: 40442649
Well, your query says to insert when exists. You miss a NOT there:
IF NOT EXISTS (SELECT xrefid FROM outlookreport.dbo.requestdoc)
0
 

Author Comment

by:desiredforsome
ID: 40442662
Here is my trigger and it is not inserting when changed. Any ideas? I know its something small

USE [outlookreport]
GO
/****** Object:  Trigger [dbo].[XREFID]    Script Date: 11/14/2014 09:26:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[XREFID]
ON [outlookreport].[dbo].[MFUSERS]
AFTER INSERT
AS
DECLARE @XREFID NVARCHAR(50)
SET @XREFID = (SELECT TOP 1 XREFID FROM OUTLOOKREPORT.DBO.MFUSERS)
 BEGIN
IF ((SELECT TRIGGER_NESTLEVEL()) > 1 )
BEGIN
   RETURN
END
 IF NOT EXISTS(SELECT  XREFID FROM OUTLOOKREPORT.DBO.REQUESTDOC)
 INSERT INTO OUTLOOKREPORT.DBO.REQUESTDOC (XREFID)
 SELECT XREFID FROM OUTLOOKREPORT.DBO.MFUSERS
 END

Open in new window

0
 

Author Comment

by:desiredforsome
ID: 40442668
THis also not working

USE [outlookreport]
GO
/****** Object:  Trigger [dbo].[XREFID]    Script Date: 11/14/2014 09:26:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[XREFID]
ON [outlookreport].[dbo].[MFUSERS]
AFTER INSERT
AS

 BEGIN
IF ((SELECT TRIGGER_NESTLEVEL()) > 1 )
BEGIN
   RETURN
END
 IF NOT EXISTS(SELECT  XREFID FROM OUTLOOKREPORT.DBO.MFUSERS)
 INSERT INTO OUTLOOKREPORT.DBO.REQUESTDOC (XREFID)
 SELECT XREFID FROM OUTLOOKREPORT.DBO.MFUSERS
 END

Open in new window

0
 
LVL 50

Expert Comment

by:Vitor Montalvão
ID: 40442688
I can't understand the logic.
If NOT EXISTS(SELECT  XREFID FROM OUTLOOKREPORT.DBO.MFUSERS) --> This means that if is true then the table MFUSERS is empty (no records).

INSERT INTO OUTLOOKREPORT.DBO.REQUESTDOC (XREFID)
 SELECT XREFID FROM OUTLOOKREPORT.DBO.MFUSERS
--> If no records exists this won't work at all !!!!
0
 

Author Comment

by:desiredforsome
ID: 40442694
What I want it to do is look to see if the record that was inserted into MFUSERS exists in REQUESTDOC if it does then it does nothing. If it does not exists in REQUEST doc then it inserts the XREFID from MFUSERS that was inserted into REQUESTDOC.
0
 
LVL 50

Accepted Solution

by:
Vitor Montalvão earned 500 total points
ID: 40442701
Ok, that's why the script was so confused to me.
Try this one:
USE [outlookreport]
GO
/****** Object:  Trigger [dbo].[XREFID]    Script Date: 11/14/2014 09:26:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[XREFID]
ON [outlookreport].[dbo].[MFUSERS]
AFTER INSERT
AS

 BEGIN
IF ((SELECT TRIGGER_NESTLEVEL()) > 1 )
BEGIN
   RETURN
END
 IF NOT EXISTS(SELECT 1 
                FROM OUTLOOKREPORT.DBO.REQUESTDOC d
                INNER JOIN Inserted
                    ON d.XREFID = Inserted.XREFID)
 INSERT INTO OUTLOOKREPORT.DBO.REQUESTDOC (XREFID)
 SELECT XREFID FROM Inserted
 END

Open in new window

0
 

Author Closing Comment

by:desiredforsome
ID: 40442713
Thanks for your patience this is wonderful.
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Running total between 2 sql tables in Sql 6 50
SQL Query (lookup) 8 65
Load Fact table in SQL Server SSIS package 14 46
SQL Server 2012 to SQL Server 2016 24 56
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question