How to show day name in SQL Server?
No need to convert to varchar in order to get weekday.
UNION ALL
SELECT DATEADD(dd,1,CDATE),
DATENAME(dw, CONVERT(varchar, DATEADD(dw,1,CDAY))) -- No need to convert to varchar in order to get weekday.
FROM CTE_DATE
WHERE DATEADD(dd,1,CDATE) <= DATEADD(dd,-(DAY(DATEADD(mm,1,CDATE))),DATEADD(mm,1,CDATE))
you can directly get it using datename function.
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, DATEADD(dd,1,CDATE)) -- modified
FROM CTE_DATE
WHERE DATEADD(dd,1,CDATE) <= DATEADD(dd,-(DAY(DATEADD(mm,1,CDATE))),DATEADD(mm,1,CDATE))
)
SELECT * FROM CTE_DATE
You can shortly use datename()
function( used since v.2008 )
select datename( weekday, getdate() ) as day
day
------
Friday -- > "for today(2019-04-26)"
Demo
or as in your case :
with t(cdate) as
(
select '2019-04-01' union all
select '2019-04-02' union all
select '2019-04-30'
)
select cdate, datename( weekday, cdate ) as cday
from t;
+----------+-------+
| cdate | cday |
+----------+-------+
|2019-04-01|Monday |
|2019-04-02|Tuesday|
|2019-04-30|Tuesday|
+----------+-------+
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.