开发者

SQL Server: set NULL value to today's value

I have a column EntryDate in a 开发者_运维百科SQL Server database.

How can I set a NULL value to fill it with today's date (server time) if value was not provided in a query?


Disallow Nulls on the column and set a default on the column of getdate()

/*Deal with any existing NULLs*/
UPDATE YourTable SET EntryDate=GETDATE() WHERE EntryDate IS NULL

/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN EntryDate DATE NOT NULL

/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
    DF_YourTable_EntryDate DEFAULT GETDATE() FOR EntryDate


Update table 
set EntryDate = getdate() 
where EntryDate is null


Another solution:

Rename your table, and create a view with the same name that does the logic you want, i.e.:

CREATE VIEW TableName
AS
SELECT Column1, Column2, ... ISNULL(EntryDate, GETDATE())
FROM Old_TableName

Then you don't alter your actual data, but if you get a null value for that table it reports today's date.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜