Set default value in column IF condition is met in SQL 2008

寵の児 提交于 2019-12-08 08:43:27

问题


First of all, I'm very new with SQL query, so I apologize if I sound ignorant...

I have a database that has a stored job to drop and create a table every hour. The table looks like this, except there is data for every hour in between 1 and 24

Name         Hour1  Hour24
Point 1 OUT  4      5
Point 1 IN   26     22
Point 2 OUT  46     44    
Point 2 IN   0      0
Point 3 OUT  18     19
Point 3 IN   56     51
Point 4 OUT  111    100
Point 4 IN   0      0
Point 5 OUT  0      0
Point 5 IN   42     46
Point 6 IN   210    211

After the drop and create, the database adds a column at the end called date and sets todays date as the default. My problem is when importing the data at 12:00am, the current date is actually tomorrow. For accounting purposes, I need that data to have the same day.

I took a shot in the dark and tried this, but the syntax is all wrong...

[Date] [datetime] DEFAULT if(DATEPART(hh)=24) CONVERT(GETDATE(DATEPART(dd)-1))

Is an if statement like this possible in a create table query? Is there a better way of going about this?

Thanks for the help!


回答1:


Yes, you can set up a default value, but you want the syntax to be correct:

[date] datetime default (case when datepart(hh, getdate()) = 24 then getdate() - 1 else getdate() end)

However, I don't think you should have a datetime value in a field called "date". How about:

AsOfDate date default (case when datepart(hh, getdate()) = 24 then cast(getdate() - 1 as date) else cast(getdate() as date) end)


来源:https://stackoverflow.com/questions/14632703/set-default-value-in-column-if-condition-is-met-in-sql-2008

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