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

x
?
Solved

SQL - Insert and Update Trigger

Posted on 2014-03-20
2
Medium Priority
?
333 Views
Last Modified: 2014-04-04
I need to write a trigger that will copy one field to another when there's an insert or update.  Since this insert/update is being done by the application, which I have no control over.  Is it possible to do an after trigger for just an update?

Example, there's 2 date field (Delivery_Date and Due_Date).  If Delivery_date is populated, then the trigger will also populate Due_Date.  However, if it's an update and Due_date is already populated, then do not update

Here's what I'm thinking of, but does not work.

Create Trigger dbo.Update_date
On dbo.Purchase_line
After Update
Update Purchase_line
Set   Delivery_date  = Due_Date
From Purchase_line PL
Where PL.Order_ID in (Select I.Order_Id from Inserted I Where I.Order_ID = PL.Order_ID  
                                        I.Line_no = PL.Line_no)
           and PL.Due_Date Is Null

The above, I want it to execute after the Insert/Update is done then fire the above to do an update if "Due_Date" is Null only.
0
Comment
Question by:holemania
2 Comments
 
LVL 70

Accepted Solution

by:
Scott Pletcher earned 2000 total points
ID: 39942757
Create Trigger dbo.Update_date
On dbo.Purchase_line
After /*Insert*,/ Update --uncomment if you also want to default Due_Date on an Insert
As
Set Nocount On
Update Purchase_line
Set   Delivery_date  = Due_Date
From Purchase_line PL
Inner Join inserted I
    On I.Order_ID = PL.Order_ID AND I.Line_no = PL.Line_no
Where
PL.Due_Date Is Null
Go
0
 

Author Closing Comment

by:holemania
ID: 39978196
Thanks that worked nicely.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

885 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