• Sean Lange (10/3/2013)


    How can you write a constraint that won't allow an update to Col3 when the value of Col2 = 0?

    I am not sure if this is what you and/or the OP had in mind but give it a try.

    CREATE TABLE #usTab1

    (

    Col1 INT IDENTITY(1,1) NOT NULL PRIMARY KEY,

    Col2 Tinyint DEFAULT (0) NOT NULL,

    Col3 NVARCHAR(30) NOT NULL

    );

    insert #usTab1

    select 0, 'Allows change'

    union all

    select 1, 'Can''t change'

    ;

    select * from #usTab1;

    ALTER TABLE #usTab1 WITH NOCHECK

    ADD CONSTRAINT my_chk CHECK (Col2=0 AND Col3=Col3) ;

    GO

    UPDATE #usTab1

    SET Col3 = 'works'

    WHERE Col1 = 1;

    GO

    UPDATE #usTab1

    SET Col3 = 'A bust'

    WHERE Col1 = 2;

    GO

    BEGIN TRANSACTION T1;

    ALTER TABLE #usTab1

    DROP CONSTRAINT my_chk;

    insert #usTab1 select 0, 'Allows change';

    insert #usTab1 select 1, 'Can''t change';

    ALTER TABLE #usTab1 WITH NOCHECK

    ADD CONSTRAINT my_chk CHECK (Col2=0 AND Col3=Col3) ;

    COMMIT TRANSACTION T1;

    select * from #usTab1;

    GO

    DROP TABLE #usTab1;

    I'd need to check whether the scope of the TRANSACTION covers the ALTER TABLE statements but I think it does.

    Also, this won't work if you're doing a MERGE that UPDATEs and INSERTs.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St