我正在尝试学习SQL,但我无法让DATEPART工作。我的表是付款,列名是BirthDay。
问题:我在这里无法解决什么问题?
问题是为什么SQL语句会抛出错误。由于读取,他们发现了一个简单的语法问题。
@columnName有什么作用?拥有tableName.ColumnName或者某个人是否应该使用@columnName。
1970-04-05
代码:
SELECT DATEPART(yyyy,p.BirthDay) AS OrderYear,
DATEPART(mm, p.BirthDay) AS OrderMonth,
DATEPART(dd, p.BirthDay) AS OrderDay
FROM Payment as p;
这是屏幕的图像。
答案 0 :(得分:5)
您需要在orderDay之后丢失逗号:
SELECT DATEPART(yyyy,p.BirthDay) AS OrderYear,
DATEPART(mm, p.BirthDay) AS OrderMonth,
DATEPART(dd, p.BirthDay) AS OrderDay
FROM Payment as p;
答案 1 :(得分:2)
最简单的方法是将日期转换为字符串。您还有逗号的语法错误。
DECLARE @BirthDay DATETIME
SET @Birthday='04/05/05'
SELECT
*,
CAST(OrderYear AS NVARCHAR(4))+'-'+CAST(OrderMonth AS NVARCHAR(2))+'-'+CAST(OrderDay AS NVARCHAR(2))
FROM
(
SELECT DATEPART(yyyy,@BirthDay) AS OrderYear,
DATEPART(mm, @BirthDay) AS OrderMonth,
DATEPART(dd, @BirthDay) AS OrderDay
)AS X
答案 2 :(得分:2)
正如评论和类似答案中所提到的,您可能只是遇到了一些语法错误。名称,OrderDay
之后的逗号。
在屏幕截图中,您还有一些语法错误,
SELECT p.BirthDay
datepart(dd,p.BirthDay) as Year
from payment as p;
应该读更像这样的东西:
SELECT p.BirthDay, -- Note the comma!
DATEPART(dd,p.BirthDay) AS Day --dd = day
FROM Payment as p;
作为使用DATEPART()
的替代方法,您可以使用快捷键功能:
SELECT YEAR(p.BirthDay), MONTH(p.BirthDay), DAY(p.BirthDay)
FROM Payment p