Home Forums SQL Server 2008 T-SQL (SS2K8) column value balancing (copy previous value <> NULL) RE: column value balancing (copy previous value <> NULL)

  • This form of the update statement has special rules for running in this manner. They MUST be followed, or your data can be made wrong. See comments in code for more information.

    DECLARE @Owned INT = 0,

    @OnRent INT = 0,

    @Sequence INT = 0,

    @Category CHAR(3);

    -- This form of the UPDATE statement has some particular rules.

    -- See Jeff Moden's article at http://www.sqlservercentral.com/articles/T-SQL/68467/

    -- for a complete discussion of how this works, and all of the rules for utilizing it.

    WITH SafetyCheck AS

    (

    SELECT Category,

    Class,

    Location,

    RowNo,

    Owned,

    OnRent,

    Sequence = ROW_NUMBER() OVER (ORDER BY Category,Class,Location,RowNo)

    FROM dbo.TestTable

    )

    UPDATE t

    SET @Sequence = CASE WHEN Sequence = @Sequence + 1 THEN @Sequence + 1

    ELSE 1/0 END,

    @Owned = Owned = IsNull(Owned, @Owned),

    @OnRent = OnRent = ISNULL(OnRent, @OnRent),

    @Category = Category -- ANCHOR COLUMN

    FROM SafetyCheck t WITH (TABLOCKX)

    OPTION (MAXDOP 1);

    select * from dbo.TestTable;

    Wayne
    Microsoft Certified Master: SQL Server 2008
    Author - SQL Server T-SQL Recipes


    If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
    Links:
    For better assistance in answering your questions
    Performance Problems
    Common date/time routines
    Understanding and Using APPLY Part 1 & Part 2