I set up a table yesterday with the following code. the code ran with no error messages reported and the table appeared correctly set up in object explorer.
Create Table PriceTable
(Airport_IACO_Code Varchar (4) NOT NULL,
Airline_IACO_Code Varchar (3) NOT NULL,
FlightDate Date NOT NULL Default Getdate(),
DepTime Time NOT NULL Default DATEADD(hour, 6, GETDATE()),
Price Smallmoney,
RouteDiscontinuedOrCommences Varchar (15),
)
GO
However on checking the table today the FlightDate which has the Getdate() default is showing yesterdays date
and
the the DepTime column which has the DateAdd Default is showing an incorrect time of 18:45:02. the current time as I am writing this is 11.04.
Does anyone know what is wrong.
Thanks in advance for any help offered.
You may find the handling of defaults a bit counter-intuitive in SQL Server. The syntax is:
DEFAULT constant_expression
It so happens that SQL Server extends the definition of constant_expression to include non-deterministic scalar functions, such as getdate(). These are functions that return a different value each time they are called, even with the same arguments. The definition in the documentation is:
Only a constant value, such as a character string; a scalar function
(either a system, user-defined, or CLR function); or NULL can be used
as a default.
However, SQL Server does not extend the definition to expressions of such functions. Instead, the expression is evaluated when the table is created and a constant value is inserted.
Unfortunately, one way to accomplish what you want is using a trigger. Alternatively, you could leave the value as NULL and create a computed column to calculate the date six hours hence:
create table . . .
_DepTime time,
DepTime as (cast(dateadd(hour, 6 _DepTime) as time) )
Related
I have three tables in database. I have the column Operation_Date in all of them. I set the column default value to (GETDATE()), and its data type is VARCHAR(50) and I don't have any coding in my C# Windows application that inserts value to Operation_Date.
Issue: When I insert rows to tables the operation_Date separates month, day and year with space like this (MAY 2 2020). I get two spaces after month and one space after days.
I tried to make a query on SQL Server to insert and the same problem occurs. I tried changing data type to datetime but with not success.
Note: this issue occurs only in two tables. And I am pretty sure the three tables have the same settings.
Is there anyway to force a certain date format for the default value in SQL Server? And what could make this issue happen?
This is the query I used:
USE [EasyManagementSystem]
INSERT INTO [dbo].[Attendance] ([Employee_No], [Present], [Leave], [Othe_Leave], [Month], [Year])
VALUES ('l-8068', 30, 0, 0, 'MAY', 2020)
Huh? Why would you be storing a date as a string. That is just wrong. There is a perfectly good data type for dates, called date.
If you want this to be set on input, then just give it a default value. Your table creation should look like:
create attendance (
. . .
operation_date date default getdate()
);
Voila! It will just work. If you want the month or year, you can use the month() and year() functions.
Hi I created a table in which one column is of date type and also works as PK. I tried to insert value 2009-01-07 into this column and had this error. Isn't Date default format yyyy-mm-dd? I don't understand this.
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
This is my query:
INSERT INTO Table_Name
Values ('2009-01-07', other column values)
Your value '2009-01-07' should be converted.
Date literals are always a deep source of troubles... Best was, to use either
Unseparated: 20090107
ODBC : {d'2009-01-07'}
ISO8601 : 2009-01-07T00:00:00
But your format is short ISO 8601 and should work...
Some possible reasons:
Other values in your VALUES list
a trigger
a constraint
As a_horse_with_no_name stated in comment: Without a column list after INSERT INTO Table(col1, col2, ...) There is a great risk to state your values in a different order thus pairing values with the wrong columns...
Invalid (but good looking) dates such as 2016-06-31
Or a - well known - issue with SQL-Server. Sometimes the order of execution is absolutely not the way one expected it. There are several issues with conversion errors...
What you can try
Use ODBC format (which is treated as DATETIME immediately)
DECLARE a variable with this value and put it in place
Thank you all for the prompt replies. I read and tried all of them and found out why.
'2009-01-07' can be inserted into a Column with "Date" as data type if no CONSTRAINT has issue with that;
my problem was caused by a CHECK constraint on that column.
Originally I set CONSTRAINT as
Column_Name = 'Wednesday'
After I modified it to
DATEName(dw,[Column_Name]) = 'Wednesday'
the inserting began to work.
Thanks again.
I am using MSSQL SERVER. The questions I am asking might be silly but I want some valid answers. So here is my question:
I have a table with some columns. I have taken default in some column like 0 (for INT column), GETDATE() (for DATE column). Now one of my colleague said that taking Getdate() as default will increase overhead so better to pass datetime by INSERT statement. Is it true?
Is it not applicable to 0 or 1 (for INT column)?
How does it create overhead?
int default 0 or 1 is a value like hardcode.
but, getdate () like function to know the date on the computer server of SQL Server.
so, when the insert statement, the column with the default getdate () will look for the value prior to the server computer before the command insert is run.
I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?
GETDATE() is a date and time in SQL Server.
Run SELECT GETDATE() to verify this.
What is the datatype of your field? If it's DATE then it will not hold time values as well.
One easy way is to give the field a default constraint:
create table YourTable
(
... other columns ...
CreateDt datetime default getdate(),
... other columns ...
)
A disadvantage of this method is that you can overwrite the value by specifying it in an insert clause.
Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.
SYSDATETIME() will get the current date and time.
Make sure the data type of the column is datetime, and not just date or it won't be able to hold a datetime.
Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.
The question
Is it possible to ask SSIS to cast a value and return NULL in case the cast is not allowed instead of throwing an error ?
My environment
I'm using Visual Studio 2005 and Sql Server 2005 on Windows Server 2003.
The general context
Just in case you're curious, here is my use case. I have to store data coming from somewhere in a generic table (key/value structure with history) witch contains some sort of value that can be strings, numbers or dates. The structure is something like this :
table Values {
Id int,
Date datetime, -- for history
Key nvarchar(50) not null,
Value nvarchar(50),
DateValue datetime,
NumberValue numeric(19,9)
}
I want to put the raw value in the Value column and try to put the same value
in the DateValue column when i'm able to cast it to Datetime
in the NumberValue column when i'm able to cast it to a number
Those two typed columns would make all sort of aggregation and manipulation much easier and faster later.
That's it, now you know why i'm asking this strange question.
============
Thanks in advance for your help.
You could also try a Derived Column component and test the value of the potential date/number field or simply cast it and redirect any errors as being the NULL values for these two fields.
(1) If you just simply cast the field every time with a statement like this in the Derived Column component: (DT_DATE)[MYPOTENTIALDATE] - you can redirect the rows that fail this cast and manipulate the data from there.
OR
(2) You can do something like this in the Derived Column component: ISNULL([MYPOTENTIALDATE]) ? '2099-01-01' : (DT_DATE)[MYPOTENTIALDATE]. I generally send through '2099-01-01' when a date is NULL rather than messing with NULL (works better with Cubes, etc).
Of course (2) won't work if the [MYPOTENTIALDATE] field comes through as other things other than a DATETIME or NULL, i.e., sometimes it is a word like "hello".
Those are the options I would explore, good luck!
In dealing with this same sort of thing I found the error handling in SSIS was not specific enough. My approach has been to actually create an errors table, and query a source table where the data is stored as varchar, and log errors to the error table with something like the below. I have one of the below statements for each column, because it was important for me to know which column failed. Then after I log all errors, I do a INSERT where I select those records in SomeInfo that do not have an errors. In your case you could do more advanced things based on the ColumnName in the errors table to insert default values.
INSERT INTO SomeInfoErrors
([SomeInfoId]
,[ColumnName]
,[Message]
,FailedValue)
SELECT
SomeInfoId,
'PeriodStartDate',
'PeriodStartDate must be in the format MM/DD/YYYY',
PeriodStartDate
FROM
SomeInfo
WHERE
ISDATE(PeriodStartDate) = 0 AND [PeriodStartDate] IS NOT NULL;
Tru using a conditional split and have the records where the data is a date go along one path and the other go along a different path where they are updated to nullbefore being inserted.