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!
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