我有一个在sql中返回datetime格式的查询:
SELECT time_in
FROM job_punch_card
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
这会返回2014-2-15 07:36:32.000
之类的结果,但我只想要时间部分,而不是日期。我可以从SQL Server获取当前时间,如:
SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond
但我无法将此应用于我自己的查询。如何从上面的time_in
表中仅检索时间?
答案 0 :(得分:2)
在输出列上使用相同的CONVERT
函数:
SELECT CONVERT(VARCHAR(8), time_in, 108) AS time_in
FROM job_punch_card
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
答案 1 :(得分:1)
如果您需要CAST
类型,请使用TIME
。如果你必须对结果集进行任何计算,这将使事情变得更容易。
SELECT CAST(time_in AS TIME(0)) AS time_in
FROM job_punch_card
etc., etc.
答案 2 :(得分:0)
几乎完全相同的方式:
SELECT CONVERT(VARCHAR(8), time_in, 108)
FROM job_punch_card
WHERE
emp_key=47 and
punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
答案 3 :(得分:0)
尝试:
SELECT CONVERT(VARCHAR(8),time_in,108) AS time_in_time_only
FROM job_punch_card
WHERE emp_key=47
and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
或者:
SELECT CAST(time_in AS TIME) AS time_in_time_only
FROM job_punch_card
WHERE emp_key=47
and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
后者的优点是时间数据类型而不是字符串,这对你正在做的事情很重要。