I am trying to use a case statement that will change any rows that have a date previous to today's date and return these rows as ' ' value and then format the date as dd/MM/yyy hh:mm
I have tried using this:
CASE
WHEN AppointmentDate1 > getdate() THEN ' '
WHEN AppointmentDate1 IS NULL THEN ' '
ELSE AppointmentDate1
END AS [Appointment]
But when I run the query I get this error message:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
How do I make this work? And then how do I change to desired format? (AppointmentDate1 is currently in SQL format, e.g. '2019-05-22 10:00:00')
A case expression returns a single value. It evaluates all the return clauses and chooses the one based on precedence. Dates have a higher precedence than strings, so your failure is because ' ' (a space) cannot be converted to a date.
If you want a date as the result, then use NULL. In this case, you could do:
(CASE WHEN AppointmentDate1 < getdate() THEN AppointmentDate1
END) AS Appointment
If you want a string, then convert to a string:
(CASE WHEN AppointmentDate1 < getdate()
THEN CONVERT(VARCHAR(10), AppointmentDate1, 121)
ELSE '' -- I would just use an empty string
END) AS [Appointment]
I chose style 121. You might have another style that you like. Or use FORMAT().
Related
My function works throughout the year, to respond with the next payment date of the month for a scheduled transaction. When spanning over to next year however, it fails with "Conversion failed when converting date and/or time from character string."
The first date is the start of a chosen month. The second date is the due date of a transaction, an entry from a list of many transactions with dates. It works all year until I get past the end of the year.
How would I fix this to respond with the correct date?
SELECT dbo.NextPaymentDate('2/1/2017', '1/30/2017')
returns 2/28/2017
SELECT dbo.NextPaymentDate('2/1/2017', '12/30/2016')
returns
Conversion failed when converting date and/or time from character string
Code:
--SELECT dbo.NextPaymentDate('2/1/2017','12/30/2016')
ALTER FUNCTION [dbo].[NextPaymentDate]
(#RegisterDate DATE, #PaymentDueDate DATE)
RETURNS DATE
AS
BEGIN
DECLARE #returnDate DATE, #MonthDiff int
SET #MonthDiff = MONTH(#RegisterDate) - MONTH(#PaymentDueDate)
SELECT #returnDate =
CAST(CONVERT(varchar, YEAR(#RegisterDate)) + '-'
+ CONVERT(varchar, MONTH(#RegisterDate)) + '-'
+ CONVERT(varchar, DAY(DATEADD(mm, #MonthDiff, #PaymentDueDate))) AS DATE)
RETURN #returnDate
END
Seems the issue was with the #MonthDiff, it was returning a negative value and the casting was creating a double negative, literally, --, with the datepart separators
I changed to this, and ran a few tests and seems to work for many date variations
SET #MonthDiff = ABS(DATEDIFF(MONTH, #RegisterDate, #PaymentDueDate))
I have a query in SSMS which is returning 1900-01-01, how can I use a CASE WHEN accurately to replace 1900-01-01 with '' (a blank not a null).
CAST(ISNULL(CAST(CONVERT(DATE, cmmt.[CmmtExpirationDate], 101) AS NVARCHAR(20)), '') AS DATE) AS [Cmmt Expiration Date]
Result: 1900-01-01
I tried this but no luck (terrible syntax):
CASE
WHEN (CAST(ISNULL(cast(convert(Date, cmmt.[CmmtExpirationDate] , 101) as nvarchar(20)), '') = '1900-01-01')
THEN ''
ELSE CAST(ISNULL(cast(convert(Date, cmmt.[CmmtExpirationDate] , 101) as nvarchar(20)),'') AS DATE
END
The result of your expression needs to have a fixed data type. DATE is not possible, since '' is not a valid date. nvarchar(20) would be an option, but that means that your result will be a string even if it is not 1900-01-01.
Once you accept that, the solution is simple:
CASE WHEN cmmt.[CmmtExpirationDate] = '1900-01-01'
THEN CONVERT(nvarchar(20), cmmt.[CmmtExpirationDate])
ELSE CONVERT(nvarchar(20), '')
END
You might want to specify the desired output format as a third parameter to the first CONVERT statement.
(I assume that CmmtExpirationDate is of type DATE, because if it isn't, it should have been mentioned in the question.)
You can use try_convert as below:
try_convert(date, case when datecolumn='' then null else datecolumn end)
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".
I wrote a procedure which actually searches a record.
when i execute it, it gives an error which says:
Conversion failed when converting date and/or time from character string.
Statement:
((CONVERT(varchar, DATEPART(YYYY, Tbl_Contract.ContractDate), 101)) = #Year or #Year = '')
It appears that you are converting the date to a year value :
DATEPART(YYYY,#ContractDate)
and then trying to convert that back to a date :
CONVERT(varchar, DATEPART(YYYY, #ContractDate),101)
You might try this : EDIT
datepart(yyyy, CONVERT(datetime, #ContractDate))
Since ContractDate is a Varchar you can either parse directly with
SubString(ContractDate, x, 4) = #YearString
or you can encapsulate the condition
Case when IsDate(ContractDate) = 1
then ((CONVERT(varchar, DATEPART(YYYY, #a), 101)))
else NULL
end
I have a database in SQL Server. I do not have authorization to change any table but I can create views.
I have three varchar columns which store dates in the format YYYYMMDD. I want to create a view where the dates are converted from varchar to datetime.
Now it can be the case that instead of a date in this columns I can have empty space, NULL or the character -.
Let's take the closedDate column. If I use CONVERT(datetime, closedDate, 112)
Valid dates are converted correctly,
When there is empty space the date is converted to 1900-01-01,
NULL is kept,
The - causes a conversion error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
How can I tell to the function to convert dates just if it has valid date form and leave NULL or better an empty date(or space) in all the other cases?
Try this
CASE WHEN ISDATE(closedDate) = 1 THEN CONVERT(datetime, closedDate, 112)
ELSE NULL END closedDate
Use below code
SELECT CASE WHEN ISDATE(datecolumn)=1 THEN CONVERT(datetime, datecolumn, 103 )
ELSE null END
FROM tablename
use below for empty data
SELECT CASE WHEN ISDATE(datecolumn)=1 THEN CONVERT(datetime, datecolumn, 103 )
ELSE '' END
FROM tablename