Trouble casting string to date - sql-server

I keep getting the following error when running my query and am having trouble finding a solution.
Conversion failed when converting date and/or time from character string.
select * from creditcard
where cast(left(expdate,2) + '/01/' + right(expdate,2) as date) < '08/01/17'
and paycode <> ''
All of the dates in the table look like this '07/17'

declare #myfakedate varchar(25) = '07/17'
declare #mydatestr varchar(25)
Select #mydatestr = stuff(#myfakedate,3,0,'/01')
select #mydatestr
will give you '07/01/17'

If 2012+ user try_convert() just in case you have bogus data. Otherwise, the standard convert() should do
Example
Select *
From YourTable
Where try_convert(date,replace(expdate,'/','/01/'))<'08/01/17'

Related

Get current month record using LIKE key word

I try to get selected the current month data by using SQL Server LIKE but it not get the any result. My when I run same code in my SQL it get the original result. What is error of my query? This query I want to run in SQL Server.
SELECT EnrolledID, Date, Time
FROM dbo.view_attendance
WHERE Date LIKE '2019-08%'
ORDER BY Date,Time;
Date in the SQL Server database date is something like that 2019-08-14 00:00:00.000.
Even though you have asked for a LIKE, I would recommend using the following format:
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE [Date] >= '20190801' and [Date] < '20190901'
ORDER BY [Date], [Time];
Although there is no syntax error in the case of using LIKE over DATETIME columns, I would recommend using LIKE only when trying to parse STRING values, in search for a certain pattern.
LIKE will not work with DATETIME columns and will not return results. If your column is of type DATETIME then I recommend using the above method.
MySql does implicit conversions between data types in expressions like your case:
Date LIKE '2019-08%'
so MySql converts Date to varchar and the expression returns a valid result because both operands are treated as varchars.
You can find more here: https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html
SQL Server does not do this, so you must explicitly do the conversion or use a function like:
WHERE FORMAT(Date, 'yyyy-MM') = '2019-08'
if [Date] column is DateTime Type, try this :
declare #currentMonth int = datepart(MONTH,GETDATE())
declare #currentYear int = datepart(YEAR,GETDATE())
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE DATEPART(year,[Date]) = #currentYear And DATEPART(MONTH,[Date]) = #currentMonth
ORDER BY [Date], [Time];
or this:
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE DATEPART(year,[Date]) = datepart(YEAR,GETDATE()) And DATEPART(MONTH,[Date]) = datepart(MONTH,GETDATE())
ORDER BY [Date], [Time];

Conversion failed when converting date and/or time from character string- Not sure why?

My date Format is "MMddyy" in sql .. When am trying to do as below it through me the date conversion error but am not sure what I need to do there??
Condition Failing: My WarrantReceivedDate should be less than startDate
and DateWarrantExecuted should be >= StartDate ?
Any Help? Thanks in Advance
declare #startDate VARCHAR(6) = '010119'
declare #endDate VARCHAR(6) = '013119'
DECLARE #MyTable TABLE (
WarrantIssuingAuthority varchar(100),
CountType varchar(100),
CountRecords int
)
insert into #MyTable (WarrantIssuingAuthority, CountType, CountRecords)
select WarrantIssuingAuthority, 'WARRANTS BEGINNING OF MONTH', count(*)
from [PM].WarrantInformation
where TypeOfWarrantIssued!='COM'
and HowExecuted!='R' and HowExecuted!='U'
and DeletedIndicator!='D'
and DeletedIndicator!='P'
and CONVERT(VARCHAR(10), CAST((RIGHT(WarrantReceivedDate,2) + LEFT(WarrantReceivedDate,4)) AS DATE),112) < CONVERT(VARCHAR(10), CAST((RIGHT(#startDate,2) + LEFT(#startDate,4)) AS DATE),112)
and (DateWarrantExecuted='' or (CONVERT(VARCHAR(10), CAST((RIGHT(DateWarrantExecuted,2) + LEFT(DateWarrantExecuted,4)) AS DATE),112) >= CONVERT(VARCHAR(10), CAST((RIGHT(#startDate,2) + LEFT(#startDate,4)) AS DATE),112)))
group by WarrantIssuingAuthority
select * from #MyTable order by WarrantIssuingAuthority
We can't see the definition of your table or the data contained within but its possible that there is a value there that can't be properly converted to a date. For example, maybe there is a value 093118 which is a valid varchar value, but not a valid date.

Convert VARCHAR in format YYMMDD to YYYYMMDD and ignore invalid date formats

I have a table with a VARCHAR field called ArrivalDate in format yymmdd (such as 170202).
I am writing a query which converts it to yyyymmdd so it should become 20170202.
However my problem is that I need to cater for the case when inappropriate data is entered into the field, and my query needs to exclude that data. I am achieving this exclusion by using the ISDATE function of TSQL. I also need to select the least recent entry (I'm using order by asc for this).
I am using a variety of converts to write this query, below is my implementation with a sample table and data.
Declare #tmp TABLE (theDates VARCHAR(MAX))
INSERT INTO #tmp VALUES('170202')
SELECT TOP 1 t.theDates
WHEN (ISDATE(t.theDates) = 1) THEN CONVERT( VARCHAR(max),CONVERT(datetime t.theDates), 112)
FROM #tmp t
WHERE (ISDATE(t.theDates) = 1)
ORDER BY CAST(t.theDates as DATE)
However I do not like my approach and it occasionally fails conversion and throws an error with values such as 02/02/02 which breaks the query. Can someone please show me a better way of writing this functionality.
Much appreciated!
You can use TRY_CONVERT and CONVERT to get the correct format and convert the value. Then check that the string is exactly 6 character to prevent other formats from being returned.
SELECT
convert(char(10),convert(date, theDates, 12),112)
FROM
(values('02/02/02'),('170202')) x(theDates)
WHERE
try_convert(date, theDates, 12) is not null
and len(theDates) = 6
You can use cast(#date as datetime)
declare #date varchar(max);
set #date='170202';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
set #date='02/02/02';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
please use create function for check dateformat is Valid or not and use this fun in your query inside cash clouse.
ALTER FUNCTION dbo.f_CheckDate
(#InDate nvarchar(25))
RETURNS DATE
AS
BEGIN
declare #Return DATETIME
select #return = CASE WHEN ISDATE(#InDate) = 1
THEN #InDate
ELSE NULL
END
return #return
END
You could use TRY_CAST or TRY_CONVERT if value cannot be cast it will return NULL.
SELECT
TRY_CAST('20170228' AS DATETIME),
TRY_CAST('170228' AS DATETIME),
TRY_CONVERT(DATETIME, '20170228'),
TRY_CONVERT(DATETIME, '170228')
This works for SQL Server 2012 and newer.

Getting conversion failed error even when CONVERT function is not being called SQL

I use this command to select all the specific dates if the given variable is date, if it is not it should return all of the fields.
The commands works when #query is in the form of a date, but it returns an error:
"Conversion failed when converting date and/or time from character string."
when it is any other arbitrary string.
Code:
select * from table where
format(dateofbirth,'dd/MMM/yyyy') = Case
when ISDATE(#query)=1 then
format(CONVERT(datetime,#query),'dd/MMM/yyyy')
else
format(dateofbirth,'dd/MMM/yyyy')
Edit:
#query can be any string for eg. "1/1/2013" , "random" , "3".
The command should return all fields if #query is not in form of a date.
You can work around this problem by re-formulating your query condition like this:
declare #query as varchar(20)='blah'
SELECT *
FROM testtable
WHERE ISDATE(#query) = 0
OR CONVERT(date, dateofbirth) = CASE ISDATE(#query)
WHEN 1 THEN CONVERT(date, #query) ELSE NULL
END
Demo on sqlfiddle.
The problem is that logic operators are not short-circuited in SQL, so the optimizer treats CONVERT(date, #query) as something that it can pre-compute to speed up the query. By expanding the condition to a CASE that depends entirely on #query you can eliminate the execution of the CONVERT branch when ISDATE(#query) returns "false".

T-SQL date conversion

I have the following date format 92845 which represent hhmmss.
I would like to convert that to a datetime in SQL.
I could use something like this:
SELECT STUFF(STUFF('84936',3,0,'-'),6,0,'-')
but it appears T-SQL is not liking the hour part.
thank you!
Seems like you wrote the code in the afternoon and now it doesn't work in the morning. If you're going to stuff based on absolute positioning, you need to make sure the string is always the same length. One way to do this is by padding the string with a 0 and then taking the right-most 6 characters. Also, you need : not - for H/M separators.
SELECT STUFF(STUFF(RIGHT('0' + '84936', 6),3,0,':'),6,0,':');
Result:
08:49:36
Now it can be converted to a datetime:
SELECT CONVERT(DATETIME, STUFF(STUFF(RIGHT('0' + '84936', 6),3,0,':'),6,0,':'));
Result:
1900-01-01 08:49:36.000
I don't know where 92845 is currently stored. If it's in a variable, then something like this will work:
declare #t varchar(6) = '92845';
declare #fullt char(6) = RIGHT('000000' + #t,6)
select DATEADD(second,
SUBSTRING(#fullt,1,2) * 3600 +
SUBSTRING(#fullt,3,2) * 60 +
SUBSTRING(#fullt,5,2),0)
Result:
1900-01-01 09:28:45.000
If it's in a column of a result set, then you can do similar manipulations using e.g. subqueries.
try this:
declare #t varchar(6) = '134524'
select CASE WHEN len(#t)=5 then convert(datetime,convert(varchar(10),CAST(getdate() as date))+' '+'0'+LEFT(#t,1)+':'+SUBSTRING(#t,2,2)+':'+SUBSTRING(#t,4,2))
else convert(datetime,convert(varchar(10),CAST(getdate() as date))+' '+LEFT(#t,2)+':'+SUBSTRING(#t,3,2)+':'+SUBSTRING(#t,5,2)) end

Resources