Set value of the column to default for NULL values

时间:2015-06-26 09:57:28

标签: sql sql-server tsql

I have a table with a column which has default value to 0. However when null is inserted to this table, I want it to set it to default.

As the insert query is generic and used by other databases too, I cannot make any changes to the insert statement.

Can I have constraints or case statement on create table, so that default 0 value is inserted whenever null is passed.

3 个答案:

答案 0 :(得分:3)

You can do an update using a trigger on insert.

CREATE TRIGGER [dbo].[YourTriggerName]
   ON  [dbo].[YourTable]
   AFTER  INSERT 
AS 
BEGIN
      UPDATE t SET YourCol = 0
      FROM YourTable t
           JOIN Inserted i ON t.Id = i.Id
      WHERE i.YourCol IS NULL 
END

答案 1 :(得分:3)

If you can not change an insert statement you have no way other then creating an instead of insert trigger:

CREATE TRIGGER trTableName 
ON SchemaName.TableName
INSTEAD OF INSERT
AS
BEGIN

    INSERT INTO TableName (ColumnA, ColumnB, ...)
    SELECT ISNULL(ColumnA, 0), ISNULL(ColumnB, 0), ...
    FROM INSERTED

END

答案 2 :(得分:1)

Inserting null is the same as inserting a specific value, and so the default value is bypassed.
To use the default setting the insert statement shouldn't insert anything to this column.

If you can't use Coalesce (value, 0) in the select bit of the into statement, try using it in your select queries to disguise the result.