问题
i need a trigger that prevent some data from inserting in table According to a condition , before inserting any row in the table like this code
create Trigger trigger_name
on table_name
for insert
AS
Begin
if (true)
insert into table_name values ()
End
回答1:
Use Instead Of Insert trigger and exists operator to validate the rows that meet the condition
CREATE TRIGGER trigger_name
ON table_name
Instead OF INSERT
AS
BEGIN
INSERT INTO table_name
SELECT *
FROM inserted
WHERE EXISTS (SELECT 1
WHERE condtion = true)
END
回答2:
Instead of Trigger
(using INSTEAD OF CLAUSE)
This type of trigger fires before SQL Server starts the execution of the action that fired it. This is differ from the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include the actual insert/update/delete to the table.
Syntax:
CREATE TRIGGER trigger_nameON {table|view}
[WITH ENCRYPTION|EXECUTE AS]
{FOR|AFTER|INSTEAD OF}
{[CREATE|ALTER|DROP|INSERT|UPDATE|DELETE ]}
[NOT FOR REPLICATION]
AS sql_statement [1...n ]
Trigger should something like
CREATE TRIGGER trigger_name
ON table_name
instead OF INSERT
AS
BEGIN
IF (true)
INSERT INTO table_name VALUES ()
END
回答3:
Did you try using check constraints instead of triggers ? This is their intended purpose. Applying simple conditions for preventing inserting/updating data that does not fit your business logic.
http://www.techonthenet.com/sql_server/check.php
来源:https://stackoverflow.com/questions/27659572/trigger-for-prevent-inserting-data-according-to-a-condition