Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trigger with External Logging

Status
Not open for further replies.

NHW

Programmer
Mar 16, 2004
24
0
0
HK
Hi all. I'm new to writing triggers and simply couldn't think of getting something to work.

I am using DTS to import a csv file into a table called "tblChild". There is only one column, "ParentID", to insert. Some ParentID may already exist in the current tblChild. So the trigger should only add those ParentID that are new. In addition, a row should be added only if the ParentID also exists in a table in another database (dbParent.tblParent.ParentID). If it doesn't exist, write to a text file for logging.

Can triggers handle these tasks? Thanks in advance.

-NHW
 
You can do it all with T-SQL. Use bcp to import the CSV file into a staging table. Then INSERT the new parents that are in the remote table.
Code:
INSERT tblChild(ParentID)
SELECT s.ParentID
FROM tblStaging s
  INNER JOIN dbParent.tblParent r
    ON r.ParentID = s.ParentID
WHERE NOT EXISTS(SELECT * FROM tblChild c
                 WHERE c.ParentID = s.ParentID)
Then use bcp to log the non-existent ParentIDs using this query.
Code:
SELECT s.ParentID
FROM tblStaging s
WHERE NOT EXISTS(SELECT * FROM dbParent.tblParent r
                 WHERE r.ParentID = s.ParentID)

--John [rainbow]
-----------------------------------
Behold! As a wild ass in the desert
go forth I to do my work.
--Gurnie Hallock (Dune)
 
Thanks John. But is it possible to log the non-existing ParentID into a text file as this information may need to be viewed by users who don't have access to the database.
 
Use bcp to log the non-existent ParentIDs using this query.

Check out BCP in Books Online. It will allow you to quickly export the result set of a query to a text file.

Code:
SELECT s.ParentID
FROM tblStaging s
WHERE NOT EXISTS(SELECT * FROM dbParent.tblParent r
                 WHERE r.ParentID = s.ParentID)

--John [rainbow]
-----------------------------------
Behold! As a wild ass in the desert
go forth I to do my work.
--Gurnie Hallock (Dune)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top