gpt4 book ai didi

sql - 如何在 SQL Server 中显示日期名称?

转载 作者:行者123 更新时间:2023-12-02 15:43:59 25 4
gpt4 key购买 nike

我在 SQL 服务器上有一个查询

我想显示如下:

CDATE      | CDAY
2019-04-01 | Monday
2019-04-02 | Tuesday
... | ......
2019-04-30 | Tuesday

但是我发现错误如下:

Conversion failed when converting date and/or time from character string.

如果有人可以帮忙

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

最佳答案

您很快就可以使用datename()函数(自 v.2008 起使用)

  select datename( weekday, getdate() ) as day

day
------
Friday -- > "for today(2019-04-26)"

Demo

或如您的情况:

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|
+----------+-------+

关于sql - 如何在 SQL Server 中显示日期名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com