在OpenQuery调用中使用datetime变量转换失败

时间:2015-09-08 19:27:31

标签: sql sql-server

我正在运行链接查询,我很难将计算变量注入OPENQUERY调用。

我在Stack Overflow上发现了一些似乎指向数据类型不匹配的解决方案,但是我不能在OPENQUERY调用之外复制错误,所以这让我很困惑。 / p>

以下是有问题的查询:

SELECT name
FROM OPENQUERY ( [OLTP\SQL2014],
'USE master; DECLARE @FROMDATE datetime2(7) = dateadd(dd, -10, Sysdatetime());     
DECLARE @ToDate datetime2(7) = sysdatetime();
EXEC (''SELECT name from sys.tables 
  INNER JOIN sys.partitions
       ON sys.tables.object_id = sys.partitions.object_id 
WHERE  sys.tables.create_date BETWEEN '''' + @FromDate + '''' AND '''' + @ToDate + 
  '''' AND sys.tables.name LIKE ''''%EXCEPTION%''''
   AND NOT sys.tables.name LIKE ''''%AUDIT''''
   AND sys.partitions.rows <> 0 '')'
)

我是否需要放弃在OPENQUERY内使用变量?

1 个答案:

答案 0 :(得分:2)

而不是使用丑陋的字符串连接而EXEC使用参数化EXEC sp_executesql,如:

SELECT name
FROM OPENQUERY ( [OLTP\SQL2014],
  'USE master;
  DECLARE @FromDate DATETIME = DATEADD(dd, -10, SYSDATETIME());     
  DECLARE @ToDate   DATETIME = SYSDATETIME();
  DECLARE @sql NVARCHAR(MAX) = 
      N''SELECT name 
          FROM sys.tables 
          JOIN sys.partitions
            ON sys.tables.object_id = sys.partitions.object_id 
          WHERE sys.tables.create_date BETWEEN @FromDate AND @ToDate
            AND sys.tables.name LIKE ''''%EXCEPTION%''''
            AND NOT sys.tables.name LIKE ''''%AUDIT''''
            AND sys.partitions.rows <> 0'';

   EXEC [dbo].[sp_executesql]
       @sql
       ,N''@FromDate DATETIME, @ToDate DATETIME''
       ,@FromDate
       ,@ToDate;
');

编辑:

SELECT name
FROM OPENQUERY ( [OLTP\SQL2014],
  'USE master;
  DECLARE @FromDate DATETIME = DATEADD(dd, -10, SYSDATETIME());     
  DECLARE @ToDate   DATETIME = SYSDATETIME();

  EXEC [dbo].[sp_executesql]
       N''SELECT name 
          FROM sys.tables 
          JOIN sys.partitions
            ON sys.tables.object_id = sys.partitions.object_id 
          WHERE sys.tables.create_date BETWEEN @FromDate AND @ToDate
            AND sys.tables.name LIKE ''''%EXCEPTION%''''
            AND NOT sys.tables.name LIKE ''''%AUDIT''''
            AND sys.partitions.rows <> 0''
       ,N''@FromDate DATETIME, @ToDate DATETIME''
       ,@FromDate
       ,@ToDate;
');