Unable to insert into the table - sql

declare #Sampledate table (SampleDate datetime)
insert into #Sampledate
select
'04/07/2018 18:18:29'
I get an error:
Conversion failed when converting date and/or time from character string.
AS of getting the data like this from the browser to SQL. How to resolve it?
Please try inserting in the same manner. Date in one row and time in another row. Need a quick response, please.

Need to remove the line feed or carrier return if you insist on putting date and time on two lines.
declare #sampledate table (sampledate datetime)
insert into #sampledate select REPLACE('04/07/2018
18:18:29',CHAR(10),'')
OR
declare #sampledate table (sampledate datetime)
insert into #sampledate select REPLACE(REPLACE('04/07/2018
18:18:29',CHAR(10),''),CHAR(13),'')

If this is for SQL Server - you have two options:
Option 1: use the ISO-8601 date format in your string literal to be independent of the language/regional settings in your SQL Server instance - this is recommended to be used always - it just helps avoid trouble:
INSERT INTO #Sampledate(SampleDate)
SELECT '2018-04-07T18:18:29'
This is a date in YYYY-MM-DDTHH:MM:SS format - it will always work, regardless of your settings in SQL Server - while many other formats will work sometimes, but not other times.
Option 2: use the DATETIME2(n) datatype (instead of DATETIME) which is a lot less "finicky" about the string literal format being inserted.
DECLARE #Sampledate TABLE (SampleDate DATETIME2(0));
INSERT INTO #Sampledate(SampleDate)
SELECT
'04/07/2018 18:18:29'
This may work - again, it's less finicky, but the string literal is still dependent on your language/regional settings - it might work - or not. Using option #1 is definitely your safer bet - but also, I'd recommend using DATETIME2(n) over DATETIME (as of SQL Server 2008), too - it's just the better datatype (uses less space, offer a larger date range, less tricky about inserting values into - only benefits, really!)

Related

try_cast and cast differing results. The conversion of a date data type to a datetime data type resulted in an out-of-range value

I have a two SQL 2017 databases.
Database 1 contains table(a) with a column of datatype "date"
Database 2 contains table(b) with a column of datatype "datetime"
I'm doing a basic insert statement from "table a" into "table b" using
SELECT CAST(si.InceptionDate AS datetime).
This is currently failing with the error
"The conversion of a date data type to a datetime data type resulted in an out-of-range value."
If I change the insert statement to
SELECT TRY_CAST(si.InceptionDate AS datetime) this now works. This makes sense in theory however the datetime column in "table b" doesn't contain any NULLs and isn't missing any records from "table a". How can try_cast manage to successfully change the datatype but cast can't?
I think this has something to do with the data being selected from "table a" because I created a dummy table with the "date" data type on database 2 and inserted into this first before inserting insert "table b" and this works no problem.
Can anyone think of a reason for this??? It has me stumped :(
Presumably, your query is more complicated than you are showing.
My guess is that some of the values would result in conversion errors but these rows are filtered out of the final result. SQL Server has a habit of pushing expressions before filtering clauses. Once consequence is that errors on rows that would be filtered out cause the query to fail.
There are 2 things that could be contributing here, and without any sample data, I can only guess which (though it could be both).
Firstly, let's address the 2 functions you have, TRY_CAST and CAST. TRY_CAST cannot return the error you have; if the conversion fails then NULL is returned. That is by design and the documentation will have told you that.
Next, you have 2 different data types, datetime and date. datetime is an older data type and is suseptical to problems based on the LOGIN's LANGUAGE setting. Specifically, for datetime (and smalldatetime) the format yyyy-MM-dd is not unambiguous. This can be reproed with the below:
SET LANGUAGE ENGLISH; --American
SELECT CAST('2021-01-13' AS datetime); --Works
GO
SET LANGUAGE BRITISH; --English; we speak ENGLISH in England...
SELECT CAST('2021-01-13' AS datetime); --Fails
GO
This doesn't happen with date:
SET LANGUAGE ENGLISH; --American
SELECT CAST('2021-01-13' AS date); --Works
GO
SET LANGUAGE BRITISH; --English; we speak ENGLISH in England...
SELECT CAST('2021-01-13' AS date); --Works
GO
Again, as we have no sample, then either 1 or both of these factors are contributing.

Why can't I insert yyyymmdd (stored as text) to a date column

This has been asked many times before and I tried quite a bit before posting this question. I have 2 columns on my SQL Server table where the dates are stored as CHAR(8) yyyymmdd format. When I try to insert this to another table with date column, I get:
Conversion failed when converting date and/or time from character string.
The typecasting that I used is:
,CAST(convert(char(10),qrda.BillFromDate,120) AS DATE) AS [BillStartDate]
,CAST(convert(char(10),qrda.BillToDate,120) AS DATE) AS [BillEndDate]
With the above code, I am trying to make it SQL Server readable date format and then typecasting it to DATE so that I can insert it to the destination table without any other transformations. Not sure where I am going wrong with this.
Since date are stored in the following format yyyyMMdd you can insert these values without any need to use CONVERT or CAST functions, since this format can be implicitly converted to DATE.
If the data contains invalid values such as 00000000, you can use TRY_CONVERT or TRY_PARSE function to convert these values to NULL
Example:
CREATE TABLE #TBLTEMP(datecolumn DATETIME)
INSERT INTO #TBLTEMP(datecolumn)
VALUES ('20180101')
INSERT INTO #TBLTEMP(datecolumn)
VALUES (TRY_PARSE('00000000' as DATETIME))
SELECT * FROM #TBLTEMP
Result:
From the example above, you can see that 20180101 was inserted succesfly without any casting, while TRY_PARSE function converted the invalid value 00000000 to NULL.
You can use the following syntax:
INSERT INTO TargetTable(DateColumn)
SELECT TRY_PARSE([CharColumn] as DATETIME
FROM SourceTable
References
Understanding SQL Server’s TRY_PARSE and TRY_CONVERT functions
TRY_PARSE (Transact-SQL)
Sorry for the trouble folks, but looks like this is bad production data where some values are literally '00000000'. I dont know how this flows into our system, but since the source table columns are CHAR(8), this is a valid value. Not so much for me.

tSQL - convert nvarchar(8) to time only

I am using Microsoft SQL Server Management Studio to manipulate Public transport system database.
I have a table in database named 'dbo.tblStop_times', two columns of which should be of data type time. At the moment, they are both nvarchar and they have data stored in a pattern like this - "07:39:00" (without quotes)
I had same question with date columns as well, but found a solution for that on stackoverflow just few hours back.
Below works fine for conversion of nvarchar column to date column.
ALTER TABLE tblCalendar ALTER COLUMN [start_date] DATE NOT NULL;
I am not sure if what I want is achievable or not, because the above mention conversion works just fine, I assume it might be possible.
What I have atm is - nvarchar(8), what I want it to be is sql time data type, something like hh:mm:ss [and if possible - without trailing nnnnnn - nanoseconds component]
You should be able to do:
ALTER TABLE tblStop_times ALTER COLUMN start_time TIME NOT NULL;
Here is a rextester.
EDIT:
If you don't have valid time values, then you have a problem. You should first look for the values:
select col
from tblStop_times
where try_convert(time, col) is null;
This will show you the values that cannot be converted. If you like, you can NULL them out so the alter will work:
update tblStop_times
set col = NULL
where try_convert(time, col) is null;

Converting datetime to short date from a declared table in sql

This is my first question on StackOverflow so I apologize for this most likely being formatted incorrectly. I am very new to sql language and am having trouble with the following query:
I have a declared table with one row selecting for a datetime (OccurrenceGroupID) and would like to have that date show up with short date formatting in the query results.
--Select for Occurrence Group
Declare #A3 table (OccurrenceGroupID datetime)
insert into #A3
select OccurrenceGroup as OccurrenceGroup,
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
from tblOccurrenceGroup
where occurrencegroupid = #occurrencegroupid
I get the error message "Column name or number of supplied values does not match table definition."
Any help would be much appreciated.
Thanks.
Your error is because you are selecting two columns and trying to insert the result set into a table with only one column.
Regardless of this you are converting a datetime to a varchar presumably for presentation reasons and then wanting to insert it into a column of type datetime which doesn't make much sense. Always leave the formatting of dates to the client application.
you have declared it as datetime
Declare #A3 table (OccurrenceGroupID datetime)
so it expects a date and a time you the go on to say
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
you then say convert the varchar as MM/DD/YYYY therefor it is contradictory to your first statement

How to prevent CAST errors on SSIS?

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.