Conversion failed when converting date and/or time from character string. T-Sql - tsql

I have a varchar column in my database called ref003 which stores datetime like the below
2021-04-04 20:01:03
Here, date format is like yyyy-MM-DD
When I execute the below select query I am getting error
SELECT *
FROM FileIndex
WHERE CAST(CONVERT(CHAR(30), CONVERT(DATETIME, Ref003, 105), 101) AS DATE)
BETWEEN CAST(CONVERT(CHAR(10), CONVERT(DATETIME, '01-01-2021', 105), 101) AS DATE)
AND CAST(CONVERT(CHAR(10), CONVERT(DATETIME, '31-12-2021', 105), 101) AS DATE)
And the error is
Msg 241, Level 16, State 1, Line 5 Conversion failed when converting
date and/or time from character string.
What is the problem here and how can I solve this problem?

First, for the conversion you need to convert to VARCHAR, not DATE. Note this expression:
CONVERT(VARCHAR(10), CAST(<your date value> AS DATE), 20)
With that in mind, you can clean your query up like so:
--==== Easily consumable sample data
DECLARE #thetable TABLE (someid INT, thedate DATETIME);
INSERT #thetable
VALUES(1,'2021-04-04 20:01:03'),(2,'2021-06-04 22:01:05'),(1,'2021-04-29 10:31:11');
--==== Solution
SELECT t.*, FormattedDate = fmt.Dt
FROM #thetable AS t
CROSS APPLY (VALUES(CONVERT(VARCHAR(10), CAST(t.thedate AS DATE), 20))) AS fmt(Dt)
WHERE t.thedate BETWEEN '20210401' AND '20210501';
Returns:
someid thedate FormattedDate
----------- ----------------------- -------------
1 2021-04-04 20:01:03.000 2021-04-04
1 2021-04-29 10:31:11.000 2021-04-29

Related

How to fetch only year from date in postgresql table

I have a table like this in postgresql:
Name
DOB
ABC
'2011-03-03'
XYZ
'2009-01-01'
What is the query that I should use to get the output data in the below format(only year instead of date) also I want to retrieve data that is greater than 2010 only:
Name
DOB
ABC
'2011'
Format DOB using to_char.
select "Name", to_char(DOB, 'yyyy') DOB
from the_table
where extract('year' from DOB) > 2010;
If DOB is character rather than date type then it has to be first cast to date:
select "Name", to_char(DOB::date, 'yyyy') DOB
from the_table
where extract('year' from DOB::date) > 2010;
If your date represented as text has "month/day/year" format then use to_date to convert it to date.
select "Name", to_char(to_date(DOB, 'mm/dd/yyyy'), 'yyyy') DOB
from the_table
where extract('year' from to_date(DOB, 'mm/dd/yyyy')) > 2010;
Unrelated but do not store dates as formatted text. You have data type date for this.

Concatenate Date and Time

I m trying to concatenate Date and Time using the below line but i m getting an error. Any help?
Time column type: Time (0)
CONVERT(date, getdate()) + ' ' + CONVERT(time(0), [Time]) AS Date_Time
The data types date and varchar are incompatible in the add operator.
There are a number of ways to do that - one of them is to convert both parts to DateTime which supports the add (+) operator:
SELECT CAST(CAST(GetDate() As Date) As DateTime) + (CAST([Time] As DateTime) As Date_Time
The casting of GetDate() to Date and back to DateTime resets the time portion to midnight.
I use the below and it is working:
CAST(CONVERT(date, getdate()) AS nvarchar) + ' ' + CAST(CONVERT(time(0), [Time]) AS nvarchar) AS Date_Time
Thanks to the rules for data type precedence you are trying to convert ' ' to a data type compatible with date and time, hence the error.
The next problem is that a date does not have a time component, hence to combine the two you need to use a datetime or similar data type.
declare #Time as Time = '12:30:00';
select #Time as Time,
-- Get today's date as a date .
Cast( GetDate() as Date ) as Today,
-- Get today's date and convert it to a datetime so that the time can be added.
Cast( Cast( GetDate() as Date ) as DateTime ) + Cast( #Time as DateTime ) as DateAndTime;
Note that time values need to be converted to datetime (or another compatible type) before adding the values. Curiously, SQL Server 2008 didn't require that step.

Convert String "Friday June 1, 2018" to Date

I have a column in database from imported file in the format Friday June 1, 2018 and trying to format to a valid date conversion from varchar to date.
I have tried cast and convert with no success
SELECT CAST([Course date] as DATETIME)
FROM [dbo].[Test]
SELECT CONVERT(datetime, [Course date], 103)
FROM [dbo].[Test]
I expected conversion to type 103 UK dd/mm/yyyy
TRY_CONVERT seems to be able to handle your date string. Note that the name of the day is superfluous, and is not needed to determine exactly what the date is. So, we can remove it using base string functions.
WITH yourTable AS (
SELECT 'Friday June 1, 2018' AS datecol
)
SELECT
datecol AS input,
TRY_CONVERT(datetime, STUFF(datecol, 1, CHARINDEX(' ', datecol), '')) AS output
FROM yourTable;
Demo

convert int to datetime in sybase

This works perfectly on the server (sql server 2012) for a julian date of 5 digits
select cast (column1 as DATETIME) FROM mytable
How to cast an int to datetime in sybase?
And which would be the best way, since I have a large table and I have to minimize the time i'm going to be using the server under the query.
I saw here: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1570/html/sqlug/sqlug645.htm
that it is allowed to convert from int to varchar and from varchar to smalldate.
So maybe something like this, but i don't know the syntax for sybase:
declare #convDate varchar (200)
set #convDate = 'SELECT top 100 CONVERT( varchar (200), column1, 104 )as someCol FROM dbo.mytable'
select cast (#convDate as DateTime) as newDate into #myTemp from ?
Assuming date is in YYYYMMDD format. Use below:
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, col1)) AS someCol FROM dbo.mytable
Internal numbers representing dates in Excel are a continuous sequence of integers from Jan 1 1900, which is number one. Hence, a solution is to use the function DATEADD to sum your integer (minus one) to Jan 1 1900. In this query, " " is the same as "Jan 1 1900" as this is the Sybase ASE default.
select dateadd(day, column1 - 1, " ") from mytable /* Probably wrong */
But I tested and got a one day difference. The result of this is Jul 13 2015, but Excel shows Jul 12 2015 instead.
select dateadd(day, 42197 - 1, " ")
IMHO, Excel is wrong, as it shows Feb 29 1900 for the number 60, but 1900 (contrary to 2000) is not a leap year. Sybase ASE is correct; this gives Feb 28 1900 and Mar 1 1900:
select dateadd(day, 59 - 1, " "), dateadd(day, 60 - 1, " ")
Assuming you had to take Excel convention, then just subtract two instead of one:
select dateadd(day, column1 - 2, " ") from mytable /* Bizarre but maybe OK */

Most Performant Way to Convert DateTime to Int Format

I need to convert Datetime fields to a specifically formatted INT type. For example, I want
2000-01-01 00:00:00.000 to convert to 20010101.
What is the most performant way to make that conversion for comparison in a query?
Something like:
DATEPART(year, orderdate) * 10000 + DATEPART(month, orderdate) * 100 +
DATEPART(day, orderdate)
or
cast(convert(char(8), orderdate, 112) as int)
What's the most performant way to do this?
Your example of cast(convert(char(8), orderdate, 112) as int) seems fine to me. It quickly gets the date down to the format you need and converted to an int.
From an execution plan standpoint, there seems to be no difference between the two.
You can try with TSQL builtin functions.
It's not .NET tick compatible but it's still FAST sortable and you can pick your GRANULARITY on demand:
SELECT setup.DateToINT(GETDATE(), 4) -- will output 2019 for 2019-06-06 12:00.456
SELECT setup.DateToINT(GETDATE(), 6) -- will output 201906 for 2019-06-06 12:00.456
SELECT setup.DateToINT(GETDATE(), 20) -- will output 20190606120045660 for 2019-05-05 12:00.456
CREATE FUNCTION setup.DateToINT(#datetime DATETIME, #length int)
RETURNS
BIGINT WITH SCHEMABINDING AS
BEGIN
RETURN CONVERT(BIGINT,
SUBSTRING(
REPLACE(REPLACE(
REPLACE(REPLACE(
CONVERT(CHAR(25), GETDATE(), 121)
,'-','')
,':','')
,' ','')
,'.','')
,0
,#length+1)
)
END
GO
Is this what you need
SELECT REPLACE(CONVERT(VARCHAR(10),'2010-01-01 00:00:00.000',101),'-','')
When you pass '2010-01-01 00:00:00.000' directly in your code, the SELECT statement looks at it as a string and not a datetime data type. Its not the same as selecting a datetime field directly.
There is no need to do outer CAST because SQL Server will do implicit conversion, here is a proof.
DECLARE #t DATETIME = '2010-01-10 00:00:00.000',#u INT
SELECT #u = CONVERT(CHAR(8), #t, 112)
IF ISNUMERIC(#u) = 1
PRINT 'Integer'