简体   繁体   中英

SQL Server : set a default value for Insert Into query when parameter is null

I'm trying to do an insert query like follow:

Insert Into table1 (column1, column2)
Values (#value1#, #value2#)

But let's say, I want to default column2 to 2/19/2013 when the parameter #value2# is null. How would I achieve that?

I'm using Ibatis framework, and the insert statement is in a XML file, which is used in a db file that is called from the controller.

这可能是您要寻找的:

ISNULL(#value2#,'2/19/2013')

If you can't change insert statements which are coming from an XML file, you might consider creating a trigger

CREATE TRIGGER table1_Insert ON table1
INSTEAD OF INSERT
AS
INSERT INTO table1 (column1, column2)
    SELECT column1, ISNULL(column2,'2/19/2013') FROM INSERTED;

Then if try to insert a NULL

INSERT INTO table1 VALUES (1, NULL);

You'll have

| COLUMN1 |   COLUMN2 |
-----------------------
|       1 | 2/19/2013 |

Here is sqlfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM