Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Simple SQL Insert Trigger

Posted on 2014-11-10
15
Medium Priority
?
169 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
  • 8
  • 5
  • 2
15 Comments
 
LVL 52

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 52

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 52

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 52

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 52

Accepted Solution

by:
Vitor Montalvão earned 2000 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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

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

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

963 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