Today, I will be looking at how INSTEAD OF TRIGGERS can be used to make our VIEW correctly work with a DELETE statement.
I will be using the [AUTOS] sample database for this demonstration. The [VW_JOIN_MAKES_2_MODELS] view will be enhanced with a instead of trigger so that delete action can be perform on two tables at the same time.
The enclosed script has code to perform the following actions in the AUTOS database.
- 5A – Remove aggregate view
- 5B – Reload tables with good data
- 5C – Create a instead of trigger (insert)
- 5D – Test insert actions of instead of trigger
- 5E – Create a instead of trigger (delete)
- 5F – Test delete actions of instead of trigger
- 5G – Create a instead of trigger (update)
- 5H – Test update actions of instead of trigger
Our focus today will be on 5E – defining the instead of delete trigger and 5F – performing unit testing on said trigger.
Like most Data Definition Language (DDL) constructs, a user defined trigger has three operations associated with it: CREATE TRIGGER, ALTER TRIGGER and DROP TRIGGER.
Since our view joins data between two tables, we need to know if data is going to be deleted from the 1 = MODELS, 2 = MAKES or 3 = BOTH tables.
With the instead of insert trigger, we could use the physical data in the inserted table to determine what action to perform. The instead of delete table has the deleted table for reference; However it only shows potential records affected by the delete statement.
How do we determine what table to delete from?
We are in luck since the DBCC INPUTBUFFER command can help us. Calling this function with the current session id returns a table containing information about the event. I used a table variable below to hold the information. We can find the exact TSQL statement that was used when the trigger fired.
By parsing this string, we can find the WHERE clause of the delete statement. Thus, finding what table to delete from.
Here are some ground rules for our view users. One requirement of the user is to use the primary key (make or model id) or natural key (make or model name) in the WHERE clause. Deleting from the model table has no dependencies. Deleting from the make table can only occur if no model records exist. An exception to this rule is a delete from both tables when only one record exists in both. Any broken requirements will end up in a error.
The code below defines the INSTEAD OF DELETE trigger.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
-- -- Create a instead of trigger (delete) -- -- Remove existing trigger IF OBJECT_ID('DBO.TRG_CORRECT_DEL_ACTION_4_MAKES_2_MODELS') IS NOT NULL DROP TRIGGER [DBO].[TRG_CORRECT_DEL_ACTION_4_MAKES_2_MODELS]; GO -- Create instead of trigger CREATE TRIGGER [DBO].[TRG_CORRECT_DEL_ACTION_4_MAKES_2_MODELS] ON [DBO].[VW_JOIN_MAKES_2_MODELS] INSTEAD OF DELETE AS -- Author: John Miner -- Date: Jan 2013 -- Purpose: Perform the correct delete action for a view. BEGIN -- Declare local variables DECLARE @VAR_WHICH_TABLE INT; DECLARE @VAR_TSQL NVARCHAR(4000); DECLARE @VAR_VAL1 INT; DECLARE @VAR_VAL2 INT; -- Declare input buffer variable DECLARE @VAR_BUFFER TABLE ( [EventType] NVARCHAR(30), [Parameters] INT, [EventInfo] NVARCHAR(4000) ); -- Find the tsql that fired the trigger INSERT INTO @VAR_BUFFER EXEC sp_executesql N'DBCC INPUTBUFFER(@@spid) WITH NO_INFOMSGS'; -- Parse TSQL to get WHERE clause SELECT @VAR_TSQL = UPPER(ISNULL(B.EventInfo, '')) FROM @VAR_BUFFER B; SELECT @VAR_VAL1 = CHARINDEX('WHERE', @VAR_TSQL, 1); IF (@VAR_VAL1 > 0) SELECT @VAR_TSQL = SUBSTRING(@VAR_TSQL, @VAR_VAL1, LEN(@VAR_TSQL) - @VAR_VAL1); -- Action being performed PRINT 'INSTEAD OF DELETE ACTION - '; -- Find out what is being modified SELECT @VAR_WHICH_TABLE = 0; IF ( (CHARINDEX('MODEL_ID', @VAR_TSQL, 1) > 0) OR (CHARINDEX('MODEL_NM', @VAR_TSQL, 1) > 0) ) SELECT @VAR_WHICH_TABLE = @VAR_WHICH_TABLE + 1; IF ( (CHARINDEX('MAKER_ID', @VAR_TSQL, 1) > 0) OR (CHARINDEX('MAKER_NM', @VAR_TSQL, 1) > 0) ) SELECT @VAR_WHICH_TABLE = @VAR_WHICH_TABLE + 2; -- Key fields are null IF (@VAR_WHICH_TABLE = 0) BEGIN -- Action being performed PRINT ' NO VALID KEYS SUPPLIED. '; -- Raise an error on this action RAISERROR('Either makers or models id or name must not be null when deleting data. Please try again.', 16, 1) END; -- Delete from models table IF (@VAR_WHICH_TABLE = 1) BEGIN -- Action being performed PRINT ' DELETE FROM MODELS. '; -- Perform the delete DELETE FROM [DBO].[MODELS] WHERE MODEL_ID IN ( SELECT D.MODEL_ID FROM deleted AS D ); END; -- Delete from makes table IF (@VAR_WHICH_TABLE = 2) BEGIN -- Must be one record SELECT @VAR_VAL1 = COUNT(*) FROM deleted; -- Must not have any children SELECT @VAR_VAL2 = ISNULL(MODEL_ID, 0) FROM deleted; -- Make sure conditions are meet IF (@VAR_VAL1 = 1) AND (@VAR_VAL2 = 0) BEGIN -- Action being performed PRINT ' DELETE FROM MAKES. '; -- Perform the delete DELETE FROM [DBO].[MAKES] WHERE MAKER_ID IN ( SELECT D.MAKER_ID FROM deleted AS D ); END ELSE BEGIN -- Action being performed PRINT ' TOO MANY CHILD RECORDS EXIST. '; -- Raise an error on this action RAISERROR('There must no model records left when deleting data from makes. Please try again.', 16, 1) END; END; -- Delete from both tables IF (@VAR_WHICH_TABLE = 3) BEGIN -- Action being performed PRINT ' DELETE FROM MODELS & MAKES. '; -- Delete from child table first DELETE FROM [DBO].[MODELS] WHERE MODEL_ID IN ( SELECT D.MODEL_ID FROM deleted AS D ); -- Delete from parent table second DELETE FROM [DBO].[MAKES] WHERE MAKER_ID IN ( SELECT D.MAKER_ID FROM deleted AS D ); END; END |
Before testing the new trigger, I want to add another model record (child) to the maker table (parent). This means on data relationship with have an 1 to 2 cardinality.
1 2 3 |
-- Add data to child table INSERT INTO DBO.VW_JOIN_MAKES_2_MODELS (MAKER_ID, MODEL_NM, MODEL_YR, MSRP) VALUES (6, 'Model X', 2013, 104000); |
Lets get the negative testing out of the way by trying to delete data from the view without a natural or primary key.
1 2 |
-- Delete should fail DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS; |
The first positive test is to delete data from the MODELS table using either the natural or primary key.
1 2 3 4 5 |
-- Delete from child table DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS WHERE MODEL_NM = 'Model X'; -- Delete from child table DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS WHERE MODEL_ID = 6; |
The second positive test is to delete from the MAKES table using the natural key. We have to make sure no child record exists.
1 2 |
-- Delete from parent table DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS WHERE MAKER_NM = 'Tesla'; |
The second negative test is delete data from from the MAKES table using the primary key with one existing child record. This is a no-no according to the rules.
1 2 |
-- Delete from parent table (fails due to child record) DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS WHERE MAKER_ID = 7; |
The third positive test is to validate that deletion of data from both the MAKES and MODELS tables at the same time works. This is a new functionality that is not available in a normal view.
1 2 |
-- Delete from both tables DELETE FROM DBO.VW_JOIN_MAKES_2_MODELS WHERE MAKER_ID = 7 AND MODEL_ID = 7; |
In summary, we were able to add a INSTEAD OF DELETE trigger to our user defined view to make it function correctly with a DELETE statement. While the next article focus on making our view work correctly with an UPDATE statement, these trigger can be used for other purposes.
For instance, when designing a system that keeps track of large money transactions, we never want to actually delete a record. We just want to mark it as deleted just incase the action taken by a high level user was fraudulent. This would be another pefect use of this trigger.