且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T-SQL 如何在插入前修改值

更新时间:2022-12-12 10:50:28

基本上,使用 INSTEAD OF INSERT 触发器,您可以实现您想要的 - 只需从INSERTED 伪表,修改后插入到表中

Basically, with an INSTEAD OF INSERT trigger, you can achieve what you're looking for - just read out the data from the INSERTED pseudo table, modify it, and insert it into the table

所以你的触发器看起来像这样:

So your trigger would look something like this:

CREATE TRIGGER YourTrigger ON dbo.YourTable    
INSTEAD OF INSERT
AS
    SET NOCOUNT ON

    -- do the INSERT based on the INSERTED pseudo table, modify data as needed
    INSERT INTO dbo.YourTable(Col1, Col2, ....., ColN)
      SELECT 
          Col1, 2 * Col2, ....., N * ColN
      FROM 
          INSERTED

当然,您也可以添加例如以 WHERE 子句的形式检查该 SELECT .... FROM INSERTED 语句到例如忽略某些行 - 可能性无穷无尽!

Of course, you could also add e.g. checks in the form of WHERE clause to that SELECT .... FROM INSERTED statement to e.g. ignore certain rows - the possibilities are endless!