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

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.

Related

Inserting a value - Oracle sql date field format

From what I have seen so far, when inserting into a table that has date value such as "27-10-2004", the following format DD-MON-YYYY is used
insert into tableName values('27-Oct-2004')
Is it possible to insert the date in its original format '27-10-2004' into the table? In general how many variations of this date may be considered correct for inserting into tables (this is without using any built-in functions, just SQL)?
Use a date literal in Oracle:
insert into tableName
values (DATE '2004-10-27');
This defines a date constant using the ISO standard format YYYY-MM-DD.
If you wanted to use a specific format -- which I wouldn't recommend -- then you can convert to a date using to_date():
insert into tableName
values (to_date('27-10-2004', 'DD-MM-YYYY'));
Any particular string that you use is interpreted based on system settings, so it can vary by language and geography.
Note: When inserting a value, you should include the column names. I assume that your code is just for illustrative purposes.

How to insert Datetime with offset in SQL server?

I have following value
2020-06-16T13:41:36.000Z
How Can I insert the value into table, What is the column datatype I should use?
I have tried with datetime datatype for column, but that did not work out
The correct data type is datetimeoffset -- although datetime and datetime2 would also work (assuming the values are all in the same time zone). SQL Server stores date/times using an internal format.
create table t (ts datetimeoffset);
insert into t (ts) values ('2020-06-16T13:41:36.000Z');
select * from t;
This returns:
ts
2020-06-16 13:41:36.0000000
This is equivalent to your value but formatted using an arbitrary format. If you want to control the format, then you need to convert the value to a string. One method uses convert() with option 127:
select convert(varchar(255), t.ts, 127) from t
format() provides more flexibility.
You can also add this logic into the table definition:
alter table t add ts_iso8601 as (convert(varchar(255), t.ts, 127));
Here is a db<>fiddle.

Unable to insert into the table

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

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

inserting only date in a column in sql server

Is there a way to insert only date in a datetime column in sql server without the time?
for example
date (datetime)
===============
12-01-2000
16-02-2000
or i should store this as a varchar and cast it when retriving so that i can convert to whatever form i need.
my solution is to store it as varchar and convert it to datetime whenever needed
SELECT CONVERT(VARCHAR(10),GETDATE(),111) -- get datepart only
or
also check this post about creating date type :
create user defined data types:
create type Date from dateTime
http://weblogs.sqlteam.com/jeffs/archive/2007/10/31/sql-server-2005-date-time-only-data-types.aspx
If you are using SQLServer 2008 you can use the date data type.
The following SQL will strip out any time values and set them all to zero. So you won't need to worry whether a time value is there or not.
Select Cast(Floor(Cast(MyDateColumn as float)) as DateTime) as MyDateColumn
From dbo.MyTable
Just use smalldatetime or date. Convert your dates to your format before you update your date values or after you select date values in your app.
You can change format of date format in sql queries or in your app.
Here is a list on date formats in sql
http://www.sql-server-helper.com/tips/date-formats.aspx
Here's a link on date data types
http://databases.about.com/od/sqlserver/a/date_time.htm
Good Luck!