Solved

Simple SQL Insert Trigger

Posted on 2014-11-10
15
132 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 45

Expert Comment

by:Vitor Montalvão
Comment Utility
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 39

Expert Comment

by:lcohan
Comment Utility
"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 45

Expert Comment

by:Vitor Montalvão
Comment Utility
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
 

Author Comment

by:desiredforsome
Comment Utility
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 39

Expert Comment

by:lcohan
Comment Utility
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
Comment Utility
Would "inserted" by DB-A or DB-B?
0
 

Author Comment

by:desiredforsome
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:desiredforsome
Comment Utility
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 45

Expert Comment

by:Vitor Montalvão
Comment Utility
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
Comment Utility
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
Comment Utility
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 45

Expert Comment

by:Vitor Montalvão
Comment Utility
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
Comment Utility
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 45

Accepted Solution

by:
Vitor Montalvão earned 500 total points
Comment Utility
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
Comment Utility
Thanks for your patience this is wonderful.
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

Suggested Solutions

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now