Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL how to modify the value before insert

I find that there are only after and instead of triggers in sql server. And it is illegal to modify the values in the inserted pesudo table. Then my problem occurs: If I want to check the data which is going to be inserted into my table, and when the data violates my constraints I should modify these values to default values, how to do it ? How about updateing the values after inserted ? However, if there's no primary key or colum which is unique in my table, how can I locate the row just inserted and then update it ?

like image 886
tmj Avatar asked Dec 20 '22 22:12

tmj


1 Answers

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

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!

like image 63
marc_s Avatar answered Mar 15 '23 12:03

marc_s