Solved

SQL Server trigger to preserve an existing value

Posted on 2014-09-26
6
150 Views
Last Modified: 2014-09-29
I have a database field that stores a tracking number for shipments. Occasionally we send the order out in 2 shipments. When we process the 2nd shipment, our shipping software writes the new tracking number into the tracking field removing the tracking number that was already there.
I want to know the syntax to write a trigger for SQL Server that would evaluate the TrackingNumber1 field on update and, if there was already a tracking number in TrackingNumber1, it would capture it and move it to TrackingNumber2. The final result would be that I have both tracking numbers captured and available to me.
Can this be done and how?
Thanks -
0
Comment
Question by:GenesisTech
  • 3
  • 3
6 Comments
 
LVL 13

Expert Comment

by:Russell Fox
ID: 40346934
"DELETED" and "INSERTED" are what SQL Server calls the original data and the new data, respectively - they're essentially both virtual tables. This will concatenate any number of new tracking numbers as long as [TrackingNumber2] is big enough:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER trgKeepTrackingNumber
   ON ShippingTable
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	UPDATE shp
		SET [TrackingNumber2] = [TrackingNumber2] + ', ' + old.[TrackingNumber1]
	FROM ShippingTable shp
		JOIN INSERTED new
			ON shp.[ID] = new.[ID]
		JOIN DELETED old
			ON shp.[ID] = new.[ID]
	WHERE old.[TrackingNumber1] <> new.[TrackingNumber1]


END
GO

Open in new window

0
 

Author Comment

by:GenesisTech
ID: 40346943
Russell -

Awesome. Delivered as requested and as needed. THANK YOU!

I will plug this in and give it a try and get back to you.
0
 

Author Comment

by:GenesisTech
ID: 40346945
Russell,

I do have a question that I did not think about. If we mess up the shipment and I go into the record and Delete the Tracking Number will the trigger you wrote still move the tracking number to TrackingNumber2 even though I deleted it?
0
Zoho SalesIQ

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

 
LVL 13

Accepted Solution

by:
Russell Fox earned 500 total points
ID: 40347006
If you delete just the tracking number, i.e. clear out that field, then yes, it will add the old, deleted number to TrackingNumber2. If you delete the entire shipping record, then no, the whole record will go away. If you don't want it to add the deleted tracking number, then you can exclude that in the trigger:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE TRIGGER trgKeepTrackingNumber
   ON ShippingTable
   AFTER UPDATE
AS 
BEGIN
	SET NOCOUNT ON;

	UPDATE shp
		SET [TrackingNumber2] = [TrackingNumber2] + ', ' + old.[TrackingNumber1]
	FROM ShippingTable shp
		JOIN INSERTED new
			ON shp.[ID] = new.[ID]
		JOIN DELETED old
			ON shp.[ID] = new.[ID]
	WHERE old.[TrackingNumber1] <> new.[TrackingNumber1]
		AND COALESCE(old.[TrackingNumber1], '') <> ''

END
GO

Open in new window

A word to the wise: triggers are often overlooked when someone else has to troubleshoot an issue. Make sure you document the trigger and what it does, preferably in the code you use to update the tracking number. Otherwise, people just see weird behavior and don't know why!
0
 
LVL 13

Expert Comment

by:Russell Fox
ID: 40347014
Also, FWIW, it would be better to create a stored procedure that's called to update the tracking number value, and the proc can handle this rather than a trigger. That's assuming you have any control over the UI code, of course. We use a billing system that I created along with our .Net guy, and he has no SQL code other than to call stored procedures and functions that I've created.
0
 

Author Closing Comment

by:GenesisTech
ID: 40350152
Russell,

Excellent answer - works great. Thanks for your help!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
SQL help 5 48
sql Audit table 3 48
Help with SQL joins 9 38
SQL query to summarize items per month 5 28
There are some very powerful Data Management Views (DMV's) introduced with SQL 2005. The two in particular that we are going to discuss are sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats.   Recently, I was involved in a discu…
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…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 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

24 Experts available now in Live!

Get 1:1 Help Now