【问题标题】:Getting error: "Conversion failed when converting date and/or time from character string" in SQL Server出现错误:SQL Server 中的“从字符串转换日期和/或时间时转换失败”
【发布时间】:2019-06-25 11:35:19
【问题描述】:

我收到此错误:

从字符串转换日期和/或时间时转换失败。

这是我的查询

Declare @last_run date; 
Declare @current_run date;

Set @last_run = 'SELECT CONVERT (date, ''2016-06-24'')';

Set @current_run = 'SELECT CONVERT (date, SYSDATETIME()) ';

Select 
    sh.isbn_l, sh.id_k, sh.id_s, sh.data, sh.quantity, l.price, 
from 
    Book as l
inner join 
    Sales as sh on l.isbn = sh.isbn_l
where 
    sh.timestamp between @last_run and @current_run

【问题讨论】:

  • Max 给了你正确的 sql。为了解释你做错了什么:你声明了一个日期类型的变量。您试图将其初始化为字符串。即使该字符串包含一个 sql 语句,对于 db 引擎它只是一个字符串,它不会尝试执行它包含的语句以将其分配给您的日期变量。看来您想在不需要它并且无法按照您尝试的方式使用它的情况下使用动态sql。

标签: sql-server


【解决方案1】:

您不需要引号中的那些 CONVERT 语句。

Declare @last_run date; Declare @current_run date;
Set @last_run= CONVERT(DATE, '2016-06-24')

Set @current_run= CONVERT (date, SYSDATETIME());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多