Multiple column update trigger

Hi,
I want to have a history track of all data that has ever been updated in a table. Say, table1 has 100 columns and to store its data change history, I have made another table track_table1 having columns : updated_column_name, old_data, new_data, mod_time.
For storing this data history, I need to write a trigger in which I will identify all columns that has value updated and insert column's name and values in the track_table1 table.
What I currently do is checking each of 100 column's new and old value inside the trigger to find out which columns have been updated. This increases the code and also oracle has to check each 100 column's values to find out whether it is being updated.
Is there any way where oracle itself can give a list of columns which have values updated by the update statement ? so that there is no need to check old and new values of every column of the table.
I am using oracle 9i and 10g databases.
Thanks much in advance,
Kawa

kawa alkesh wrote:
So, what I get from here is : I can't get old and new values when used dynamically in trigger itself, but I can get these values dynamically when I write a script for it. Is it so ??Yes, you cannot dynamically reference the :new.column_name or :old.column_name values in a trigger. You can dynamically generate the trigger as was demonstrated in the other thread.
Also, as per the scenario explained in my first question of this thread, shall I write a script file, store it on the machine as a file and then write a trigger to call this script ? Correct me if I am wrong... I have never done this kind of thing.. so a bit confusedI don't follow. There is no need to create a script that is stored on any machine. You can write a procedure that generates the trigger, install that procedure in your database, and call the procedure to generate the trigger whenever the structure of the table changes. Whether it really makes sense to do this, rather than just writing the trigger code manually, is something you'll have to determine.
Justin

Similar Messages

  • Multiple Rows Update / Refresh Toplink Query when database trigger involved

    Hi everybody!
    I have two easy troubles for you; the platform is the same as the SRDemo Toplink version.
    1.     Multiple Rows Update: I want to update with mergeEntity method, multiple rows for an isolated table; that method receives a parameter that I try to bind with the iterator "dataProvider" but it only merges the first row, not all, any other combination returns an error.
    What I want to do is to have a form (like tabular forms in Apex) that lets me update multiple rows in a single page. ¿May anyone tell me how to do it?
    2.     Refresh Toplink Named Query: I have a list on a page with two columns. From another page, a button does an action that fires a database trigger that updates one of the columns on the list´s page. When I go back to the list, it is not updated; however, the CacheResults´s property is set to false on the iterator.
    Thanks in advance,
    Alejandro T

    I didn't use it (yet), but - you might take a look. You'll find a [url http://www.oracle.com/technetwork/developer-tools/apex/application-express/apex-plug-ins-182042.html]Timer plug-in on this page. It is a dynamic action which allows you to periodically fire other dynamic actions in the browser. For example use the timer to refresh a region every five minutes. You can perform any dynamic action you want using this infrastructure.So I was thinking: you might use it to run a dynamic action which would check whether something changed in that table (I suppose you'll know the way) (for example, a database trigger might set a flag in some table, timestamp or similar), and - if you find that something really changed - refresh the page.
    As I said, I never used it so that's pure theory. Someone else might know better, though.

  • Can I update 2(or multiple) columns in a table based on one of update col?

    Hi All,
    I have a table emp:
    empno number
    ,salary number
    ,comm number
    Now, the comm column is always a % of the salary column (but still would like to store the comm in the table as a column).
    Assuming that someone get a salary increment and I need to update the commission as well based on the new salary value, should I still use 2 update statements or is there anyway, I can achive in a single update clause itself?
    example:
    if the old values were:
    =============
    1234 10000 1000
    and if I do the following,
    update emp
    set salary = salary + 3000
    ,comm = salary * 10/100
    where empno = 1234;
    the comm value still points to the old salary value and the table looks like:
    emp:
    ===
    1234 13000 1000
    instead of:
    1234 13000 1300 (10% of the new salary - 13000)
    so, the only way to achieve this is to issue 2 update statements? Or is there any way of achieving in one single update statement? Please let me know.
    Am on Oracle 10.2.0.3.0.
    Thanks,
    Srini.

    Or you could create a after update trigger on salary column that updates comm whenever Sal updates.
    What happens if someone else issues an update on salary and forgets to update the commission? Wont you have incorect data then?
    Also, commision is a redundant column . I dont think it is a good idea to have computed values as a separate column.
    Thanks,
    Rajesh,

  • How to use update trigger in sql server 2008 with specific column

    Hello friends currently my trigger updates on table update, and I need to change this to only fire when specific column changes.
    /****** Object: Table [dbo].[User_Detail] ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[User_Detail](
    [sno] [int] IDENTITY(1,1) NOT NULL,
    [userid] [nvarchar](50) NULL,
    [name] [nvarchar](max) NULL,
    [jointype] [nvarchar](50) NULL,
    [joinside] [nvarchar](50) NULL,
    [lleg] [nvarchar](50) NULL,
    [rleg] [nvarchar](50) NULL,
    [ljoining] [int] NULL,
    [rjoining] [int] NULL,
    [pair] [int] NULL
    ) ON [PRIMARY]
    GO
    /****** Object: Table [dbo].[User_Detail] table data ******/
    SET IDENTITY_INSERT [dbo].[User_Detail] ON
    INSERT [dbo].[User_Detail] values (1, N'LDS', N'LDS Rajput', N'free', N'Left', N'jyoti123', N'SUNIL', 6, 4, 4)
    INSERT [dbo].[User_Detail] VALUES (2, N'jyoti123', N'jyoti rajput', N'free', N'Left', N'mhesh123', N'priya123', 3, 2, 2)
    SET IDENTITY_INSERT [dbo].[User_Detail] OFF
    /****** Object: Table [dbo].[User_Detail] trigger ******/
    CREATE TRIGGER triggAfterUpdate ON User_Detail
    FOR UPDATE
    AS
    declare @userid nvarchar(50);
    declare @pair varchar(100);
    select @userid=i.userid from inserted i;
    select @pair=i.pair from inserted i;
    SET NOCOUNT ON
    if update(pair)
    begin
    insert into Complete_Pairs(userid,pair)
    values(@userid,1);
    end
    GO
    /****** Object: Table [dbo].[Complete_Pairs] Script Date: 05/22/2014 21:20:35 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[Complete_Pairs](
    [Sno] [int] IDENTITY(1,1) NOT NULL,
    [userid] [nvarchar](50) NULL,
    [pair] [int] NULL
    ) ON [PRIMARY]
    GO
    my query is TRIGGER triggAfterUpdate is fired only when pair column in User_Details table is update only and when we update other column like ljoin or rjoin then my trigger is not fired
    please any one can suggest us how it can done or provide solution
    Jitendra Kumar Sr. Software Developer at Ruvixo Technologies 7895253402

    >select @userid=i.userid
    frominserted i;
            select
    @pair=i.pair
    frominserted i;
    The code above assumes a single row UPDATE.
    You have to setup the trigger for set processing like when 100 rows are updated in a single statement.
    UPDATE trigger example: http://www.sqlusa.com/bestpractices2005/timestamptrigger/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Performance of update query for single column vs multiple column

    Hi All,
    I could not find any answer for this, does it ever matter in terms of performance updating single column versus multiple column in a single update query.
    For eg. table consisting of 15 columns, what would be the difference in performance when one column is update in the single query against another update query where 15 columns are updated.
    Please do keep in mind my table columns in actually could be around 150+.
    Thanks for any information provided.

    If updated columns aren´t on where clause , then the only impact of 15 columns will be a increase on redo generation, and a possible chainning row.
    So since the redo is one of the things that have a large impact, the answer is yes.
    The performance will be slower.
    Regards
    Helio Dias.
    http://heliodias.com
    OCE SQL, OCP 9i

  • Update trigger syntax for multiple collumn update

    Hi
    I would like to create an update trigger that updates 3 collumns in another table.
    This works for one collumn:
    CREATE OR REPLACE TRIGGER DBNAME.Update_EVENT
    BEFORE UPDATE
    ON DBNAME.DB_EVENTS
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    DECLARE
    BEGIN
    UPDATE DB_EVENT_LOG ELOG
    SET
    COMPLETION_EVENT = :NEW.COMPLETION_EVENT
         WHERE :OLD.RECORD_ID = ELOG.RECORD_ID ;
    EXCEPTION
    WHEN OTHERS THEN
    -- log the error and re-raise
    RAISE;
    END ;
    but this does not work for multiple collumns:
    CREATE OR REPLACE TRIGGER DBNAME.Update_EVENT
    BEFORE UPDATE
    ON DBNAME.DB_EVENTS
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    DECLARE
    BEGIN
    UPDATE DB_EVENT_LOG ELOG
    SET
    (COMPLETION_EVENT
    , COMPLETION_DT_TM
    , COMPLETED_BY)
    =
    (:NEW.COMPLETION_EVENT
    , :NEW.COMPLETION_DT_TM
    , :NEW.COMPLETED_BY)
         WHERE :OLD.RECORD_ID = ELOG.RECORD_ID ;
    EXCEPTION
    WHEN OTHERS THEN
    -- log the error and re-raise
    RAISE;
    END ;
    What am i doing wrong?

    Try selecting from DUAL:
    SQL> CREATE TABLE emp_test AS SELECT * FROM emp
    Table created.
    SQL> CREATE OR REPLACE TRIGGER emp_trg
       AFTER UPDATE
       ON emp
       FOR EACH ROW
    BEGIN
       UPDATE emp_test
          SET (sal, comm) = (SELECT :NEW.sal,
                                    :NEW.comm
                               FROM DUAL)
        WHERE empno = :NEW.empno;
    END;
    Trigger created.
    SQL> UPDATE emp
       SET sal = 5000,
           comm = 5000
    WHERE empno = 7369
    1 row updated.
    SQL> SELECT empno,
           sal,
           comm
      FROM emp_test
    WHERE empno = 7369
         EMPNO        SAL       COMM
          7369       5000       5000

  • Update Multiple Columns when concerned about redo/undo log sizes.

    Hi ,
    I have update statements that updates multiple columns at once if any of them is changed. What I see that even though the value of column is not changed it still increases the redo size.
    Below is a sample code similar to the ones in my code. Basically I check whether there is a difference in any of the columns to be updated and update all of them.
    Is there a way to improve redo log size without splitting the update statement for every column that I will be updating. Redo/Undo log size is a concern for us..
      For i In 1.rec.Count Loop
        Update employees e
           Set e.first_name = rec(i).first_name, e.last_name = rec(i).last_name
         Where e.first_name != rec(i).first_name
            Or e.last_name != rec(i).last_name;
      End Loop;My database is 10g.

    Muhammed Soyer wrote:
    Redo/Undo log size is a concern for us..You are worried about the wrong thing.
    If you are concerned about the amount of undo and redo, you should be less concerned about the small diffrence between updating 1 or 3 columns and remove the loop that is contributing to a massive increase in both undo and redo.
    Re: global temporary table row order
    Name                                  Run1        Run2        Diff
    STAT...undo change vector size     240,500   6,802,736   6,562,236
    STAT...redo size                 1,566,136  24,504,020  22,937,884Run2 shows what adding a loop to a regular SQL statement will do to undo and redo. It made the redo used 15 times greater and the undo almost 30 times greater.

  • Issues in updating OE_ORDER_HEADERS_ALL attribute columns in trigger

    I have the requirement to update the attribute4 of the oe_order_headers_all based on certain data validations. A DFF has been defined on attribute4 as well. When i try to create a before insert trigger on oe_order_headers_all to update the attribute4 values, trigger completes without any errors, but the attribute4 is not getting updated with the data.
    Is there any restriction to insert the values on attribute columns of the Oracle base tables? Because when i tried the after update trigger the attribute columns could retain the values.
    Can somebody help me out on this issue?

    Create Or Replace Trigger OE_HEADER_TRIG_TEST
    Before insert
    ON OE_ORDER_HEADERS_ALL
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    declare
    v_customer_number ra_customers.customer_number%type;
    v_ship_to_org_id oe_order_headers_all.ship_to_org_id%type ;
    v_country_code varchar2(50);
    begin
    v_ship_to_org_id := :NEW.ship_to_org_id;
    select rac.customer_number,
    country
    into v_customer_number,
    v_country_code
    from ra_addresses_all raa,
    ra_site_uses_all ras,
    ra_customers rac
    where ras.address_id = raa.address_id
    and ras.site_use_id = v_ship_to_org_id
    and ras.primary_flag = 'Y'
    and raa.customer_id = rac.customer_id;
    :new.attribute4 := v_customer_number;
    :new.attribute5 := v_country_code;
    exception
    when others then
    raise_application_error(-20202,'Error in trigger'||sqlerrm);
    end;
    **I have verified that attributes are getting assigned in the trigger but is not stored in the table.

  • Update trigger on table fr audit purpose to record column level information

    Hi,
    I want to create a update trigger which will record data in an audit table.
    In audit table I want to have columns like old_value_of_Col and new_value_of_Col.
    This is easily achievable. But my main concern is to add three more columns having the information of:
    1) Which column was updated?
    2) Old value of column that was updated
    3) New value of column that was updated
    If possible, Also if one updates three columns for example, then in such a case. I would like to have three entries in audit table for the corresponding three columns.
    Please help.
    Thanks in advance.

    A few approaches to consider.
    First, if you are on 11g, take a look at Flashback Data Archive: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28424/adfns_flashback.htm#ADFNS01011
    Second, you can use Fine-Grained Auditing to capture DML statements and bind variables. It is not as easy to reconstruct the before/after picture, but it may be sufficient for some purposes.
    For trigger-based solutions, I have seen the approach you propose (1 row for each column changed) and it is tedious and prone to maintenance headaches. You have to write code for each column, doing compares (remembering to consider NULLs), dealing with different datatypes, etc. We used that design becasue there was an actual requirement to produce a report that needed such a structure.
    An easier trigger-based solution is to create a history table for the table you want to track, with all of the columns from the original, plus whatever else you need for housekeeping. Write an After Insert/Update/Delete trigger on your base table, and populate/insert rows into the history table:
    - For inserts, populate and insert row from the :new. values
    - For deletes, populate and insert a row from the :old. values
    - For updates, popualte and insert a row from the :old. values and another from the :new. values
    I would also have a column to designate whether this is an Insert, Delete, Update-Old or Update-New row.
    Once you have done one example, the rest are easy. If you were sufficiently motivated (I have not yet been :-) ), you could probably write a script to query DBA_TAB_COLS and generate the code.

  • Merge statement - update multiple columns from a single sub-select

    Is it possible to write in 10gR2, a MERGE statement, with UPDATE for multiple columns from a single sub_select?
    like this:
    MERGE INTO tableA
    using ( select * from temp) tmp
    on( tableA. col1 = tmp.col1)
    when matched then
    update set  ( tableA.col5,
                       tableA.col6,
                       tableA.col7) = ( select sum(col2), sum(col3), sum(col5)
                                                                                 from tableX
                                                                                where tableX.col1 = tableA.col1...)

    Hi,
    The USING clause is not a sub-query, so it can't reference columns from tables that are not in it.
    Include tableA in the USING clause if you really need to refer to it there. (It's not obvious that you do.)
    As always, it helps if you post:
    (1) The version of Oracle (and any other relevant software) you're using
    (2) A little sample data (just enough to show what the problem is) from all the relevant tables
    (3) The results you want from that data (In the case of a DML statement, such as MERGE, this will be the state of the tables when everything is finished.)
    (4) Your best attempt so far (formatted)
    (5) The full error message (if any), including line number
    Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
    If you can present your problem using commonly available tables (for example, tables in scott schema, or views in the data dictionary), then you can omit (2).
    Formatted tabular output is okay for (3).

  • UPDATE multiple columns with conditional SET parameters

    I have a procedure that updates multiple columns of a table using the procedure's parameter. Is it possible to have one update statement with conditional SET parameter?
    CREATE TABLE TEMP
    (POL_NUM NUMBER,
    OED DATE,
    TERM NUMBER,
    TRANS_CD CHAR(2));
    INSERT INTO TEMP VALUES (1, '1 AUG 2009', 12, 'NB');
    INSERT INTO TEMP VALUES (2, '4 AUG 2009', 12, 'XL');
    INSERT INTO TEMP VALUES (3, '2 AUG 2009', 12, 'RN');
    COMMIT;
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM NUMBER,
      pOED IN DATE,
      pTERM IN NUMBER,
      pTRANS_CD CHAR2)
    AS
    BEGIN
      IF pOED IS NOT NULL THEN
        UPDATE TEMP SET OED = pOED WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTERM IS NOT NULL THEN
        UPDATE TEMP SET TERM = pTERM WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTRAN_CD IS NOT NULL THEN
        UPDATE TEMP SET TRANS_CD = pTRANS_CD WHERE POL_NUM = pPOL_NUM;
      END IF;
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN
         NULL;
    END;Is it possible to replace multiple IFs from the code to have only one UPDATE statement with condition that update the column only if the passed parameter is not null? In real scenario I have more than 3 columns and I don't want to write many IF blocks.
    Please help Gurus!!
    Edited by: Kuul13 on Sep 18, 2009 1:26 PM

    Hi,
    You certainly don't want to issue separate UPDATE statements for every column; that will be really inefficent.
    SQL has several ways to implement IF-THEN-ELSE logic. CASE is the most versatile, but NVL will do everything you need for this job. You can use one of those to set a column to itself (and therefore not really update that column) when appropriate.
    For example:
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM   IN       NUMBER,
      pOED          IN   DATE,
      pTERM          IN   NUMBER,
      pTRANS_CD  IN       CHAR
    AS
    BEGIN
         UPDATE  temp
         SET     oed      = NVL (poed,       oed)
         ,     term      = NVL (pterm,       term)
         ,     trans_cd = NVL (ptrans_cd, trans_cd)
         WHERE     pol_num      = ppol_num;
      COMMIT;     -- Maybe
    END    tmp_proc;"EXCEPTION WHEN OTHERS THEN NULL" is almost always a bad idea. If there's an error, don't you want to know about it? Shouldn't you at least log a message in a warnings table or something?
    Think careflully about whether or not you want to COMMIT every time you call this procedure.
    Just as it's inefficient to issue a separate UPDATE statement for every column, it's also inefficient to issue a separate UPDATE statement for every row. If efficiency is important, it should be possible to UPDATE several rows in a single UPDATE statement, using NVL (or CASE, or COALESCE, or NULLIF, or NVL2, or ...).
    This was a very well-written question! Thanks for providing the CREATE TABLE and INSERT statements, and such a clear explanation.

  • Update multiple columns with single update statement..

    HI all,
    i am reading the columns value from different table but i want to update it with signle update statement..
    such as how to update multiple columns (50 columns) of table with single update statement .. is there any sql statement available i know it how to do with pl/sql..

    As I understood, may be this. Here i am updating ename,sal, comm columns all at once.
    SQL> select * from emp where empno=7369;
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17/12/1980 12:00:00        800                    20
    SQL> UPDATE emp
      2     SET ename = lower (ename),
      3         sal = sal + 1000,
      4         comm = 100
      5   WHERE empno = 7369;
    1 row updated.
    SQL> select * from emp where empno=7369;
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7369 smith      CLERK           7902 17/12/1980 12:00:00       1800        100         20
    SQL> UPDATE emp
      2     SET ename = (SELECT 'ABCD' FROM DUAL),
      3         sal = (SELECT 1000 FROM DUAL),
      4         comm = (SELECT 100 FROM DUAL)
      5   WHERE empno = 7369;
    1 row updated.

  • How to update multiple columns from different tables using cursor.

    Hi,
    i have two tables test1 and test2. i want to udpate the column(DEPT_DSCR) of both the tables TEST1 and TEST2 using select for update and current of...using cursor.
    I have a code written as follows :
    DECLARE
    v_mydept1 TEST1.DEPT_CD%TYPE;
    v_mydept2 TEST2.DEPT_CD%TYPE;
    CURSOR C1 IS SELECT TEST1.DEPT_CD,TEST2.DEPT_CD FROM TEST1,TEST2 WHERE TEST1.DEPT_CD = TEST2.DEPT_CD AND TEST1.DEPT_CD = 'AA' FOR UPDATE OF TEST1.DEPT_DSCR,TEST2.DEPT_DSCR;
    BEGIN
    OPEN C1;
         LOOP
              FETCH C1 INTO v_mydept1,v_mydept2;
              EXIT WHEN C1%NOTFOUND;
              UPDATE TEST2 SET DEPT_DSCR = 'PLSQL1' WHERE CURRENT OF C1;
              UPDATE TEST2 SET DEPT_DSCR = 'PLSQL2' WHERE CURRENT OF C1;
         END LOOP;
         COMMIT;
    END;
    The above code when run says that it runs successfully. But it does not updates the desired columns[DEPT_DSCR].
    It only works when we want to update single or multiple columns of same table...i.e. by providing these columns after "FOR UPDATE OF"
    I am not sure what is the exact problem when we want to update multiple columns of different tables.
    Can anyone help me on this ?

    oops my mistake.....typo mistake...it should have been as follows --
    UPDATE TEST1 SET DEPT_DSCR = 'PLSQL1' WHERE CURRENT OF C1;
    UPDATE TEST2 SET DEPT_DSCR = 'PLSQL2' WHERE CURRENT OF C1;
    Now here is the upated PL/SQL code where we are trying to update columns of different tables --
    DECLARE
    v_mydept1 TEST1.DEPT_CD%TYPE;
    v_mydept2 TEST2.DEPT_CD%TYPE;
    CURSOR C1 IS SELECT TEST1.DEPT_CD,TEST2.DEPT_CD FROM TEST1,TEST2 WHERE TEST1.DEPT_CD = TEST2.DEPT_CD AND TEST1.DEPT_CD = 'AA' FOR UPDATE OF TEST1.DEPT_DSCR,TEST2.DEPT_DSCR;
    BEGIN
    OPEN C1;
    LOOP
    FETCH C1 INTO v_mydept1,v_mydept2;
    EXIT WHEN C1%NOTFOUND;
    UPDATE TEST1 SET DEPT_DSCR = 'PLSQL1' WHERE CURRENT OF C1;
    UPDATE TEST2 SET DEPT_DSCR = 'PLSQL2' WHERE CURRENT OF C1;
    END LOOP;
    COMMIT;
    END;
    Please let us know why it is not updating by using using CURRENT OF

  • Update of multiple columns

    Hi,
    how do I update some columns of a table within one statement?
    For Example,
    My tabel has column: a,b,c,d and I want wo update column a,c,d
    Thanks hor help,
    Walter
    Edited by: user457173 on Sep 22, 2008 11:26 AM
    Edited by: user457173 on Sep 22, 2008 11:26 AM
    Edited by: user457173 on Sep 22, 2008 11:27 AM

    Nicloei W wrote:
    2nd option doesnt seems to be convincing, can give you ora query fetch more rows...I was only giving the principles on the assumption that people generally know about adding where clauses to restrict their data. It wasn't a conclusive working example, just a sample example of how to update multiple columns with a single select statement (what that select statement is, is not important).
    Some people are just pedants. ;)

  • Update Trigger and COLUMNS_UPDATED()

    Let me rephrase my question:
    I want to know if there is a faster way (probably using bit operators) to see if COLUMNS_UPDATED() in an update trigger on a table with more than 8 columns contains any column other than 1 specific column I will refer
    to as 'columnToIgnore'. I don't care about which columns are included or if the value has actually changed, only that there are other columns present.
    Original question:
    I have inherited a Sql Server database + schema and corresponding application and I have been tasked with speeding up the batch update of users in the database. After running some profiling I discovered that the reason it was slow is because of an update
    trigger on the users table. I did some “cleaning up” of the trigger and now it runs faster but I still think it could be more efficient. The objective of the trigger is to write to an Audit table any time an update takes place and any column is updated (it
    does not actually matter if the value has changed or not) with the exception of 1 specific column. Now I have the following code in the trigger which I had refactored from something much uglier.
    DECLARE @ColumnsUpdated VARBINARY(100)
    SET @ColumnsUpdated = COLUMNS_UPDATED()
    DECLARE @onlyIgnoreColumnChanged int
    SET @onlyIgnoreColumnChanged = 1
    SET @onlyIgnoreColumnChanged = 1
    IF (EXISTS(SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS Field
    WHERE TABLE_NAME = 'users'
    AND sys.fn_IsBitSetInBitmask(@ColumnsUpdated, COLUMNPROPERTY(OBJECT_ID('dbo.users'), COLUMN_NAME, 'ColumnID')) <> 0
    AND column_name !='columnToIgnore')) BEGIN
    SET @onlyIgnoreColumnChanged = 0
    END
    Ideally I would change the code to disable the trigger and do the insert myself BUT the code is old Classic ASP ( ie. VBScript with ODBC database connections) so I am not going to change any of the calling code because that would cost too much time and probably
    create more problems than I am solving.
    My proposed fix which I am unsure of how to code in SQL:
    It seems to me that there should be a way to get the proper id or position for the column and see if the column was used in the COLUMNS_UPDATED().
    If it was not used then we can set @onlynieuwchanged to 0 for the remaining code (not shown)
    If it was used then remove the bit from the COLUMNS_UPDATED() and see if it is empty
    If its empty then then we can set @onlynieuwchanged to 1 for the remaining code (not shown)
    If it’s not empty then then we can set @onlynieuwchanged to 0 for the remaining code (not shown)
    My problem is I am not sure how to go about coding this logic in SQL. I would think it would be possible with BIT operators? It would seem this could be more efficient than what I have now as it would get rid of the select statement which could slow down
    a large batch update.
    Notes
    My table has 30+ some columns so more than 8 which is relevant when working with COLUMNS_UPDATED() from what I have read. It also means that testing each column with UPDATE() would probably be more inefficient than what I have now.
    The update is called from the front end code (VBScript) which currently times out although not as much as it used to with my latest change. I cannot alter the code to run async mode and show progress, it would be easier for me to update the trigger.
    Reason for audit - we only record the user id in an audit table. This is then used to force a sync to another system outside of our source control that is used for various other tasks (mailings, views, etc). Again, I do not want to change how this system
    works, I only want to speed up the existing trigger with minimal effort.
    Sql Server version 2012, database Schema is set to Sql server 2005 compatibility mode.
    Any help would be greatly appreciated. Thank you in advance!
    -Igor

    Thank you again everyone for your input. As I mentioned there is much out of my control. This is an active application worked on by many developers and has been pieced together over the past 10+ years. It is NOT well written, the database schema has MUCH
    to be desired, and the code is the classic definition of 'spaghetti' code and multiple platforms are used to access the data, and there are millions of lines of code. There is nothing I can do about all of this which is why I am ignoring much of the advice.
    Sure, if this was a new application or something that was well written and possible to do some modifications then I would BUT it's not. If I was given 1 year of dedicated time to fix everything... well, I would probably throw it all away and start from scratch.
    Here is what I finally came up with. It is probably not  much faster, if at all, but when I started this I thought there would be a simple solution that I did not see. I will probably leave my code the way it was but will include the following for reference.
    DECLARE @bit int, @field int, @char int, @comparisonField VARBINARY(100)
    -- the following segment recreates the value contained in COLUMNS_UPDATED() if only the field nieuw was altered and stores that value in field @comparisonField
    SET @field = (SELECT COLUMNPROPERTY(OBJECT_ID('dbo.users'), 'columnToIgnore', 'ColumnID')) -- geth the field id for column nieuw
    select @bit = (@field - 1 )% 8 + 1
    select @bit = power(2,@bit - 1)
    select @char = ((@field - 1) / 8) + 1
    -- select @field AS [Field number], @char AS [Char], @bit AS [Bit] -- debug code to check the bits that are tested.
    -- Recreate the binary value of just having the field present in the columns_updated
    SELECT @comparisonField = CONVERT(VARBINARY(100),'0x' + RIGHT('000000000000000000' + RIGHT(CONVERT(VARCHAR(30), CONVERT(varbinary(1), @bit), 1), 2), @char*2), 1)
    -- if the generated value in @comparisonField is the same as COLUMNS_UPDATED() then only nieuw was updated
    IF @comparisonField <> COLUMNS_UPDATED() BEGIN
    -- code to add to the tracking table
    END
    -Igor

Maybe you are looking for

  • Move apps from one itouch to another using same computer

    I have a itouch 3g, my daughter has been playing alot of games on it, so for her upcoming brithday I brought her a itouch 3g. My question is how to get all of the games she has playing with the history transfered to her new itouch so I can get them o

  • Using dbms_lob

    Hi, I have a need to open blob_content files from wwv_document$ and read/print them in a portlet. Can i do that using dbms_blob?. If so can somebody guide me the steps to follow? Else is there any other way sicne the files are really huge and i need

  • Question about distance of a point to a segment

    The following code uses Line2D.ptSegDist in order to find the closest distance of each point from (0, 0), (0, 1)... to (100, 100). If the distance returned from the method is r (0), then the 1x1 rectangle being drawn is white, but the line drawn in t

  • Adding soap header in MX6.1

    I have a code working on MX7, it first adds soap header(username and password) then gets the response, but similar code didn't work on MX6.1. Please help. MX7 code: <cfscript> ru = XmlNew(); ru.AuthenticationHeader = XmlElemNew(ru, " http://www.mytes

  • How to center swf in all broswer windows?

    I'm having a frustrating time of this. I've tried using a table at 100% height & width in an html page with no margins, and it's content centred horixontally & vertically, but in safari it always positions the swf right at the top of the screen. I al