Reading the default for a column

  • I want to read the default defined with a column constraint, so that I can implement code similar to the following inside a trigger:

    INSERT MyTable (MyCol)

    SELECT isnull(MyCol, dbo.GetDefault(MyCol))

    This is to prevent the situation that when a NULL is explicity inserted into a column that doesn't allow NULLs but allows defaults, an error is generated.

    I had hoped that something like this would work, but it doesn't:

    INSERT MyTable (MyCol)

    SELECT isnull(MyCol, DEFAULT)

    Any ideas?

  • This was removed by the editor as SPAM

  • You can pull constraints from sysobjects where xtype=D, then hit sysobjects using the ID to find the code for the default in the text column. You could probably put something together to handle that, or just replace the default with a function that includes null handling.

    Alternatively with SQL2K, you could use an instead of trigger and separate your inserts into two groups, one containing rows where the column in question is not null, one containing rows (but not the col) where the column is null. That would let the default act normally.

    Andy

    http://www.sqlservercentral.com/columnists/awarren/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply