I'm running a linked query and I'm having a hard time injecting a calculated variable into the OPENQUERY call.
I've found a number of solutions here on Stack Overflow that seem to point to a data type mismatch, but I can't replicate the error outside of the OPENQUERY call, so it's confusing to me.
Here's the query in question:
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 '')'
)
Do I need to abandon the use of variables inside OPENQUERY?