我有一个问题,我试图将参数传递给T-SQL OPENROWSET
命令。我一直收到错误
将字符串转换为smalldatetime数据类型时转换失败
当我直接运行SELECT * FROM OPENROWSET
而不使用EXEC @laborquery
命令时,它可以工作。我认为这是我传递 @lastModifiedBeginDate
和 @lastModifiedEndDate
参数的方式中的某种语法错误。
timesheet_date
字段 SELECT
是char(10)
字段,我无法更改此字段。< / p>
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
答案 0 :(得分:1)
只需在Parenthesis
@laborquery
附近添加exec
即可
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'')'
答案 1 :(得分:1)
最后一个难题的答案是2014-12-01不是日期常数。它实际上是一个涉及整数的和,2014 - 12 - 1 = 2001. 2001是1905年6月25日的内部值。在你的日期常数周围加上单引号。