I have a query on the SQL server
I want to display as below:
CDATE | CDAY
2019-04-01 | Monday
2019-04-02 | Tuesday
... | ......
2019-04-30 | Tuesday
But I found error as below:
Conversion failed when converting date and/or time from character string.
Please if someone can help
DECLARE @V_DATE DATE = GETDATE()
;WITH CTE_DATE AS (
SELECT DATEADD(dd,-(DAY(@V_DATE)-1),@V_DATE) CDATE,
DATENAME(dw, CONVERT(varchar, DATEADD(dd,-(DAY(@V_DATE)-1),@V_DATE))) CDAY
UNION ALL
SELECT DATEADD(dd,1,CDATE),
DATENAME(dw, CONVERT(varchar, DATEADD(dw,1,CDAY)))
FROM CTE_DATE
WHERE DATEADD(dd,1,CDATE) <= DATEADD(dd,-(DAY(DATEADD(mm,1,CDATE))),DATEADD(mm,1,CDATE))
)
SELECT * FROM CTE_DATE
Your problem is:
DATENAME(dw, DATEADD(dw, 1, CDAY))
I think you intend:
DATENAME(dw, DATEADD(dw, 1, CDATE))
I would write the CTE as:
WITH CTE_DATE AS (
SELECT DATEADD(day ,-(DAY(@V_DATE)-1),@V_DATE) as CDATE,
DATENAME(dw, DATEADD(day, -(DAY(@V_DATE) - 1), @V_DATE)) as CDAY
UNION ALL
SELECT DATEADD(day, 1, CDATE),
DATENAME(dw, DATEADD(dw, 1, CDATE))
FROM CTE_DATE
WHERE DATEADD(day, 1, CDATE) <= DATEADD(day, -(DAY(DATEADD(month, 1, CDATE))), DATEADD(month, 1, CDATE))
)
SELECT *
FROM CTE_DATE;
Here is a db<>fiddle.
You don't describe what you want the code the code to do. It has unnecessary conversions to string and might be needlessly complicated for what you want to do.