Using variables with the wide table
- Last UpdatedMar 19, 2025
- 1 minute read
You cannot use variables in an OPENQUERY statement. Therefore, if you want to use variables in a query on the wide table, you must first build up the OPENQUERY statement "on the fly" as a string, and then execute it.
DECLARE @sql nvarchar(1000)
DECLARE @DateStart datetime
DECLARE @DateEnd datetime
SET @DateStart = '2001-8-29 11:00:00'
SET @DateEnd = '2001-8-29 11:11:00'
SET @sql = N'select *
FROM OPENQUERY(INSQL, ''SELECT DateTime, ReactLevel, ReactTemp, ProdLevel, BatchNumber, ConcPump, Mixer, TransferValve, TransferPump, WaterValve, ConcValve, OutputValve, SteamValve
FROM WideHistory
WHERE DateTime >= "' + CONVERT(varchar(26), @DateStart, 113) + '"
and DateTime <= "' + CONVERT(varchar(26), @DateEnd, 113) + '"
AND wwResolution = 1000
AND wwRetrievalMode = "cyclic"'') '
EXEC sp_executesql @sql