简体   繁体   中英

SQL cast char to datetime

I have the following t-sql:

set @sql = 'select id, query from '+@tablename+' where '+GETUTCDATE()+'> cast(ExpirationDate as datetime)'
execute sp_executesql @sql

I am getting this error:

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

How can i properly convert this?

Just put the function call inside the query string:

set @sql = 'select id, query from '+@tablename+' where GETUTCDATE() > cast(ExpirationDate as datetime)';

I don't see any advantage to putting it in before you call sp_executesql .

SET @sql = 
    'SELECT id, query 
    FROM '+@tablename+' 
    WHERE CAST('''+CAST(GETUTCDATE() AS VARCHAR(30))+''' AS DATETIME) 
          > CAST(ExpirationDate AS datetime)'
EXECUTE sp_executesql @sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM