Watch Webinar on Geo Capabilities of MongoDB
There are lots of questions asking whether there are before triggers in SQL Server. There are nothing called Before Triggers in SQL Server.
What is the requirement for the Before Trigger?
Let us say, you want to verify some values other table before inserting it. In SQL Server, you can use INSTEAD OF TRIGGER.
CREATE TRIGGER tr_data_before ON Table_Data
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM Tablle_Data2)
BEGIN
INSERT INTO dbo.Table_Data
SELECT *
FROM INSERTED
END
END
This was a question brought to my attention and I didn’t have an answer. After searching, I realized that there is no direct function for it. Hence I came up with following solution.
I used inserted and deleted virtual tables.
| Statement | inserted | deleted |
| INSERT | rows just inserted | |
| DELETE | rows just deleted | |
| UPDATE | modified row contents | original row contents |
With the above cases, I came up with following trigger.
CREATE TRIGGER trg_data_ins_del_upd
ON Data
FOR INSERT,DELETE,UPDATE
AS
BEGIN
DECLARE @ins int ,@del int
SELECT @ins = Count (*) From inserted
SELECT @del = Count (*) From deleted
IF @ins > 0 AND @del > 0
INSERT INTO Operation (Operation) VALUES ('Update')
ELSE IF @ins > 0
INSERT INTO Operation (Operation) VALUES ('Insert')
ELSE IF @del > 0
INSERT INTO Operation (Operation) VALUES ('Delete')
END
However, I feel in the above case, you better of having three separate triggers than loading everything to one trigger.
SQL Server Virtual images available for SQL 2008 R2 and SQL Server 2012 in 3 editions – Web, standard and enterprise. If you have an existing SQL Server license with software assurance, as an additional benefit you can move your existing license to Windows Azure and simply pay for compute and storage.
Prices are determined based on
virtual machines & cloud services / 750 compute hours per month