Why does MS SQL Server error on inserting the second row but not on the first row? - sql

I have an SQL table that will let me insert some rows with a datetime field but not all rows and I can't see why not. The error I get is
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
To try and work this out I created a temporary table with 1 colum and tried to add the two datetimes that are causing the issue.
create table #DateTimeTest ( created datetime );
I then try inserting these two rows
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12 05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
The first row is inserted without any problems, the second-row errors, but I can't understand why.
(1 row affected)
Msg 242, Level 16, State 3, Line 10
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Completion time: 2020-07-15T11:28:43.6451779+01:00
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');

Apparently, your date format is YDM rather than YMD. You can fix this in several ways.
One method is to use an unambiguous date/time format. In your case, that would include a T:
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12T05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19T05:31:00.00');
The reason this works is because the YYYY-MM-DDTHH:MI:SS format is the standard format for a date/time format in SQL Server -- unambiguously and not affected by dateformat. Similarly YYYYMMDD (note: no hyphens) is the standard, unambiguous format for a date constant in SQL Server, but YYYY-MM-DD is subject to dateformat.
A second method would be to set the dateformat to YMD:
set dateformat YMD;
Here is a db<>fiddle illustrating this.
A third method would be to explicitly extract the datetime from the string, using a function such as convert() -- and perhaps a few string operations as well.

Related

sql type conversion

I have a column datedocumented in the format YYYYMMDD and of the datatype nvarchar. I want to change the data type to datetime and update the column name exdatedocumented and alter the table using ALTER .can anyone help in this.I have tried something like this
update dbo.table2
set [DateDocumented] = convert(datetime,CAST([DateDocumented] as datetime),130)
I ended up getting error
Msg 242, Level 16, State 3, Line 1
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated
.
You should be able to just change the column type:
alter dbo.table2 alter column DateDocumented datetime;
Your column is in a format suitable for conversion. If you wanted to use default formats instead, just do:
update table dbo.table2
set [DateDocumented] = convert(datetime, CAST([DateDocumented] as datetime));
This should also allow the column to be converted to a datetime.
1st change that column name then alter table
sp_RENAME 'dbo.table2.datedocumented', 'exdatedocumented' , 'COLUMN'
go
ALTER TABLE dbo.table2
ALTER COLUMN exdatedocumented datetime;
It seems we have two things going on here. Changing the type for a column. And changing the name for a column. Let's try to keep these separate so not to confuse things. I will adress the changing of type (from varchar to datetime):
First of all: Why datetime? Why note datetime2 (with whatever fractions of seconds you want, for instance datetime2(0))? The new types for date and time has been around for 10 years now!
Anyhow, you apparently have values in your table which are not valid dates! First thing you need to do is to find those rows and handle them. Lets say that you will change to datetime2(0), if not, then just change below to datetime instead:
SELECT *
FROM dbo.Table2
WHERE TRY_CAST(DateDocumented AS datetime2(0)) IS NULL

Implicit conversion from data type varbinary to date SQL server

I have a procedure which takes a date value as parameter and then inserts the date value in a table:
CREATE PROCEDURE dbo.procInsert
#employed_on DATE
AS
BEGIN
INSERT INTO dbo.TBL(EMPLOYED_ON)
VALUES(#employed_on)
END
however i am getting this error:
Implicit conversion from data type varbinary to date is not allowed.
Use the CONVERT function to run this query.
I tried to use convert but its not working.
UPDATE
i found my mistake. i swapped the variables for insert.
i found my mistake. i swapped the variables for insert.

Revert CAST(0xABCD AS date)

I am designing a query to build an insert query from parts of the data that is in a database.
I know that you can export the whole database using SQL Server Management Studio, but I only need a part, and I need it in an automated form.
The Insert query that SSMS generates for a certain dataset would be
INSERT INTO tbl (dateCol) VALUES(CAST(0xABCD AS Date))
GO
and I am now trying to cast the date inserted by this statement back to 0xABCD.
I don't know what type 0xABCD is, so I played around:
Casting to int returns Explicit conversion from data type date to int is not allowed error
Casting to string returns ISO format, but not 0xABCD format.
Could I use ISO format from casting to string? If so, why did MS choose to use some kind of hex values with CAST, instead of universally understandable ISO date, in its own SSMS export routine?
SELECT CAST(CAST(0xABCD AS INT) AS DATETIME)
-- 2020-06-01 00:00:00.000
SELECT CAST(CAST(CAST('2020-06-01 00:00:00.000' AS DATETIME) AS INT) AS BINARY(2))
-- 0xABCD

Alter sql Table data format

I have a Nvarchar column in a database table which contains date values. Date values are stored in two formats
2008-05-20
22/04/2011
Now I need to convert this column to a date column. When I'm try the following query:
set dateformat dmy
alter table tblDocumentRevision
alter column RevisionDate date
it returns an error:
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
The statement has been terminated.
Please help me to solve this
Update the date string in the table so they all have the same format (one that SQL server can cast from) before you change the type to DateTime.

how to insert multiple values which is the output of a select query

Select
cast(ltrim(rtrim(Substring(string,charindex('my',string)+len('my')+5,
charindex('for the company',string)-charindex('my',string)+len('my')-9))) as datetime)
from table
Select
cast(ltrim(rtrim(Substring(string,charindex('company',string)+len('company')+1,
len(String)-charindex('company',string)+len('company')-9)))as varchar)
from description
this 2 queries has a set of rows as output.
I want to insert these values to another table using single insert.
What i did is:
insert into table2(orderid,orderdate)
Select
cast(ltrim(rtrim(Substring(String, len('The order number')+1,
CHARINDEX ( 'as been created at', String) - len ('as been created at')))) as int)
,
cast(ltrim(rtrim(Substring(string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9))) as datetime)
from description
but its not inserted..its showing error like The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value..
Is there any another way to insert this?
when inserting a datetime you should specify a string that is SQL compliant i.e.
'YYYY-MM-DD HH:MM:SS'
I suspect that the CAST function cant convert the type specified. However you dont need to convert to a datetime, you can simply insert the string representation of the datetime.
Other issues you may encounter are the casting of ltrim(rtrim()) to an int. LTRIM, RTRIM both return a varchar. CHARINDEX already returns an int.
Ensure your types are consistent
To insert output from your two queries into a single table, the data types and number of columns from these queries should match with that of the table. You can use convert
CONVERT(
DATETIME,ltrim(rtrim(Substring(
string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9)))
,112)
for your datetime column and try (provided your target table has a datetime column for OrderDate).