将日期参数传递给 OPENROWSET

Passing date parameters to OPENROWSET

我在尝试将参数传递给 T-SQL OPENROWSET 命令时遇到问题。我一直收到错误消息

Conversion failed when converting character string to smalldatetime data type

当我直接运行 SELECT * FROM OPENROWSET,而不使用EXEC @laborquery 命令时,它起作用了。我认为这是我传递 @lastModifiedBeginDate@lastModifiedEndDate 参数时的某种语法错误.

timesheet_date字段我是SELECTchar(10)字段,我没有办法改变这个。

DECLARE @lastModifiedBeginDate smalldatetime = 2014-12-01
DECLARE @lastModifiedEndDate  smalldatetime = getdate()
DECLARE @laborquery varchar(max)

SET @laborquery ='SELECT * FROM OPENROWSET(''SQLNCLI'', 
                                           ''Server=zzz;Database=yyy;Trusted_Connection=yes;Integrated_Security=SSPI'', 
    ''SELECT 
        a.company_code AS company_code, 
        a.employee_or_equipment_id AS employee_or_equipment_id, 
        a.timesheet_date as timesheet_date, 
    FROM  Allocated_Time a   
    INNER JOIN Company_Location b 
    ON B.company_code = A.company_code 
    WHERE work_unit_Id 
        IN (''10051862'',   ''10051863'',   ''10051868'',   ''10051959'', ''10051979'', ''10080220'')  
      AND CAST(timesheet_date AS smalldatetime) BETWEEN ' +  @lastModifiedBeginDate + ' AND ' +  @lastModifiedEndDate +  ' AND B.location=1'')'
EXEC @laborquery

只需在 exec

中的 @laborquery 周围添加 Parenthesis
EXEC (@laborquery)

并且您需要添加更多 quotes 并将您的变量转换为 varchar

SET @laborquery ='SELECT * FROM OPENROWSET(''SQLNCLI'', ''Server=zzz;Database=yyy;Trusted_Connection=yes;Integrated_Security=SSPI'', ''SELECT 
    a.company_code AS company_code, 
    a.employee_or_equipment_id AS employee_or_equipment_id, 
    a.timesheet_date as timesheet_date, 
    FROM  Allocated_Time a   
    INNER JOIN Company_Location b 
    ON B.company_code = A.company_code 
    WHERE work_unit_Id 
    IN (10051862,   10051863,   10051868,   10051959, 10051979, 10080220)  
    AND CAST(timesheet_date AS smalldatetime) BETWEEN ''''' +  
    convert(varchar(30),@lastModifiedBeginDate) + ''''' AND ''''' +  
    convert(varchar(30),@lastModifiedEndDate ) +  ''''' AND B.location=1'')'

最后一块拼图的答案是 2014-12-01 不是日期常量。它实际上是一个涉及整数的总和,2014 - 12 - 1 = 2001。2001 是 1905 年 6 月 25 日的内部值。在你的日期常量周围加上单引号。