SQL Server: set NULL value to today's value

吃可爱长大的小学妹 提交于 2019-12-11 04:57:43

问题


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?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/4315295/sql-server-set-null-value-to-todays-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!