Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF UPDATE() in SQL server trigger

If there's:

IF UPDATE (col1) 

...in the SQL server trigger on a table, does it return true only if col1 has been changed or been updated?

I have a regular update query like

UPDATE table-name     SET col1 = 'x',         col2 =  'y'   WHERE id = 999 

Now what my concern is if the "col1" was 'x' previously then again we updated it to 'x' would IF UPDATE ("col1") trigger return True or not?

I am facing this problem as my save query is generic for all columns, but when I add this condition it returns True even if it's not changed...So I am concerned what to do in this case if I want to add condition like that?

like image 972
Jason M Avatar asked Jan 29 '10 18:01

Jason M


People also ask

Can we use update in trigger?

AFTER UPDATE Trigger in SQL is a stored procedure on a database table that gets invoked or triggered automatically after an UPDATE operation gets successfully executed on the specified table. For uninitiated, the UPDATE statement is used to modify data in existing rows of a data table.

Can only use if update within a create trigger?

As mentioned earlier, the UPDATE() function can only be used within a trigger. If the purpose of using the UPDATE() function is to determine if any rows were updated in a table after an UPDATE statement, then the @@ROWCOUNT function can be used instead.

How do I check if a column is updated in a trigger?

SQL Server COLUMNS_UPDATED() Function for Triggers. This function is used to know the inserted or updated columns of a table or view. It returns a VARBINARY stream that by using a bitmask allows you to test for multiple columns.

How you get a list of updated columns in SQL Server trigger?

Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().


Video Answer


2 Answers

It returns true if a column was updated. An update means that the query has SET the value of the column. Whether the previous value was the same as the new value is largely irelevant.

UPDATE table SET col = col 

it's an update.

UPDATE table SET col = 99 

when the col already had value 99 also it's an update.

like image 181
Remus Rusanu Avatar answered Sep 24 '22 02:09

Remus Rusanu


Within the trigger, you have access to two internal tables that may help. The 'inserted' table includes the new version of each affected row, The 'deleted' table includes the original version of each row. You can compare the values in these tables to see if your field value was actually changed.

like image 29
Ray Avatar answered Sep 22 '22 02:09

Ray