首页 > 解决方案 > 在使用案例时将时间从表附加到 getdate()

问题描述

我正在尝试将时间从列附加到日期并在案例陈述中使用

getdate() at time zone 'Central Standard Time'

这是我迄今为止尝试过的

select case when 
getdate() at time zone 'Central Standard Time'  <= 
cast(cast (getdate() at time zone 'Central Standard Time'as date) as datetime) + endtime from tablename where id = 'uniqueid'
1 else 0 end

列的数据类型endtime是 nvarchar,时间的格式是21:00

这是我得到的错误

Incorrect syntax near the keyword 'from'

我也试过使用这个解决方案https://stackoverflow.com/a/700647但仍然是同样的错误。但是当我这样做时

select CAST(CAST(getdate() at time zone 'Central Standard Time' AS DATE) AS DATETIME) + endtime from tablename where id = 'uniqueid'

我得到了正确的回应2020-01-07 07:00:00.000

这似乎也很好

select case when
getdate() at time zone 'Central Standard Time' >= 
CAST(CAST(CAST(getdate() at time zone 'Central Standard Time'AS DATE) AS DATETIME) + '' + '10:00'as DATETIME)
then 1 else 0
end

返回 1

select case when 
getdate() at time zone 'Central Standard Time' <=
cast(CAST(CAST(getdate() at time zone 'Central Standard Time' AS DATE) AS DATETIME) + endtime from table where id = 'uniqueid' as datetime) 
then 1 else 0 end

返回Incorrect syntax near the keyword 'where'

我不确定我做错了什么还是限制。

标签: sqlsql-serversql-server-2017

解决方案


最大的问题是您尝试使用子查询而不使用子查询,这就是语法错误的全部内容。试试这个(为了清楚起见展开)

SELECT 
    CASE 
        WHEN getdate() at TIME zone 'Central Standard Time' <= 
            (SELECT cast(cast(getdate() at TIME zone 'Central Standard Time' AS DATE) AS DATETIME) + endtime FROM tablename WHERE id = 'uniqueid') -- Subquery
            THEN 1 
        ELSE 0 
    END

推荐阅读