{"id":1995,"date":"2012-05-07T20:00:27","date_gmt":"2012-05-07T20:00:27","guid":{"rendered":"http:\/\/craftydba.com\/?p=1995"},"modified":"2013-01-23T21:55:33","modified_gmt":"2013-01-23T21:55:33","slug":"various-triggers-part-4","status":"publish","type":"post","link":"https:\/\/craftydba.com\/?p=1995","title":{"rendered":"Various Triggers &#8211; Part 4"},"content":{"rendered":"<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/03\/plastic-tommy-gun.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/03\/plastic-tommy-gun-150x150.jpg\" alt=\"\" title=\"plastic-tommy-gun\" width=\"150\" height=\"150\" class=\"alignleft size-thumbnail wp-image-4106\" \/><\/a>Another usage of Data Modification Language (DML) triggers is the replicating data for historical tracking or data aggregation.  <\/p>\n<p>Today, I am going to expand on the AUTOS database that I created in prior articles to demonstrate such usage.  The business unit has asked us to track each macro task in the making of an automobile.  <\/p>\n<p>&nbsp;<\/p>\n<p>To accomplish this goal, I am going to add the following objects to the AUTOS database.<\/p>\n<p><span style=\"color: #008000;\">STATUS_CODE<\/span> &#8211; a coded version of the status of a given task.<br \/>\n<span style=\"color: #008000;\">MAKE_STATUS<\/span>  &#8211; for a given vehicle (VIN), what is the current status.<br \/>\n<span style=\"color: #008000;\">MAKE_HISTORY<\/span>  &#8211; all tasks and status for building a vehicle (VIN).<br \/>\n<span style=\"color: #008000;\">TRG_MAKE_STATUS_TO_HISTORY<\/span>  &#8211; a trigger that copies the current insert\/update to the history table.<\/p>\n<p>It is assumed that the following UPSERT stored procedure will be used when populating vehicle information.  <\/p>\n<pre><span style=\"color: #008000; font-size:small;\">-- Create the procedure\r\nCREATE PROCEDURE [USA].[UPSERT] (\r\n    @VehicleId [varchar](17),\r\n    @BrandId [Int],\r\n    @StartDate [datetime],\r\n    @FinishDate [datetime],\r\n    @MessageText [varchar](max),\r\n    @StatusCode [int])\r\nAS\r\nBEGIN\r\n\r\n    -- Worry about concurrency\r\n    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE \r\n\r\n    BEGIN TRAN\r\n    \r\n        -- Try the update first\r\n        UPDATE [USA].[MAKE_STATUS] \r\n        SET \r\n            [BrandId] = @BrandId,\r\n            [StartDate] = @StartDate,\r\n            [FinishDate] = @FinishDate,\r\n            [MessageText] = @MessageText,\r\n            [StatusCode] = @StatusCode\r\n        WHERE [VehicleId] = @VehicleId\r\n          \r\n        -- Did not update vehicle\r\n        IF @@ROWCOUNT = 0        \r\n        BEGIN\r\n        \r\n            -- Add new record\r\n            INSERT INTO [USA].[MAKE_STATUS] SELECT\r\n                @VehicleId,\r\n                @BrandId,\r\n                @StartDate,\r\n                @FinishDate,\r\n                @MessageText,\r\n                @StatusCode\r\n                \r\n            -- Detected error\r\n            IF @@ERROR <> 0\r\n                ROLLBACK\r\n               \r\n        END\r\n    \r\n    -- Save the transcation\r\n    COMMIT\r\n    \r\nEND\r\nGO\r\n<\/span><\/pre>\n<p>&nbsp;<\/p>\n<p>I am going to use the macro tasks for automobile making described in this <a href=\"http:\/\/www.ehow.com\/how-does_4928886_automobile-assembly-process.html\">ehow<\/a> article.  There are really no new TSQL statements being introduced with this example.  The typical CREATE, ALTER, and DROP statements are used in the <a href='https:\/\/craftydba.com\/wp-content\/uploads\/2012\/05\/move-to-history.sql_.txt'>sample code<\/a>.<\/p>\n<p>To illustrate the trigger working, I am going to show the history table, as defined below, full of data.<\/p>\n<pre><span style=\"color: #008000; font-size:small;\">-- Create MAKE HISTORY table (All Records)\r\nCREATE TABLE [USA].[MAKE_HISTORY]\r\n(\r\n    [VehicleId] [varchar](17) NOT NULL,\r\n    [BrandId] Int NOT NULL,\r\n    [StartDate] [datetime] NOT NULL,\r\n    [FinishDate] [datetime] NULL,\r\n    [MessageText] [varchar](max) NULL,\r\n    [StatusCode] [int] NULL,\r\n    [Duration] AS (datediff(second,[StartDate],[FinishDate])) PERSISTED,\r\n    CONSTRAINT [pk_Make_History] PRIMARY KEY CLUSTERED \r\n    ( \r\n        [VehicleId] ASC,  \r\n        [StartDate] ASC\r\n    )\r\n)\r\nGO\r\n<\/span><\/pre>\n<p>&nbsp;<\/p>\n<p>The resulting data rows after inserting 10 macro steps with one rework action is shown below.  It is not a coincident that I used increments of 100 seconds multiplied by the task number as the duration.<\/p>\n<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/05\/2-dml-move-2-history.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/05\/2-dml-move-2-history.jpg\" alt=\"\" title=\"2-dml-move-2-history\" width=\"790\" height=\"659\" class=\"alignleft size-full wp-image-1999\" srcset=\"https:\/\/craftydba.com\/wp-content\/uploads\/2012\/05\/2-dml-move-2-history.jpg 790w, https:\/\/craftydba.com\/wp-content\/uploads\/2012\/05\/2-dml-move-2-history-300x250.jpg 300w\" sizes=\"auto, (max-width: 790px) 100vw, 790px\" \/><\/a><\/p>\n<p>&nbsp;<\/p>\n<p>In summary, after triggers can be used to duplicate data for historical record keeping.  This history table might or might not be in the same database.  Having the history data in a different database allows for applying techniques such as data compression and read only file groups to reduce administrative overhead.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Another usage of Data Modification Language (DML) triggers is the replicating data for historical tracking or data aggregation. Today, I am going to expand on the AUTOS database that I created in prior articles to demonstrate such usage. The business unit has asked us to track each macro task in the making of an automobile. &nbsp; To accomplish this goal, I am going to add the following objects to the AUTOS database. STATUS_CODE &#8211; a coded version of the status of a given task. MAKE_STATUS &#8211; for a given vehicle&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[396,398,317,395,80,12,15,28,390,29],"class_list":["post-1995","post","type-post","status-publish","format-standard","hentry","category-db-dev","tag-after","tag-alter-trigger","tag-create-trigger","tag-dml","tag-drop-trigger","tag-free-code","tag-john-f-miner-iii","tag-sql-server","tag-triggers","tag-tsql"],"_links":{"self":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/1995","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1995"}],"version-history":[{"count":0,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/1995\/revisions"}],"wp:attachment":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1995"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1995"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1995"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}