Trigger For prevent inserting data According to a condition

北城以北 提交于 2019-12-25 18:51:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!