This is an example of using safe dynamic SQL to accomplish the task. I've tweaked the code to use a #temp
table rather than a @table
variable, because the latter can contribute to all sorts of weird performance issues, depending on usage.
I've made some guesses, and you may need to adjust to meet local conditions. I'm assuming that startDate
and dynamicCOLUMN
are supplied via stored procedure parameters.
CREATE TABLE #Temp
(
[dateTime] datetime,
Reading varchar(100)
);
DECLARE
@sql nvarchar(MAX) = N'';
SELECT
@sql += N'
SELECT
@startDate,
(
SELECT TOP (1)
N' + QUOTENAME(@dynamicCOLUMN) + N'
FROM tableABC
WHERE DateColumn >= @startDate
AND DateColumn < @tempdt
ORDER by DateColumn desc
);'
INSERT INTO
#Temp WITH (TABLOCK)
(
[dateTime],
Reading
)
EXEC sys.sp_executesql
@sql,
N'@startDate datetime',
@startDate;
- I use QUOTENAME to avoid potential SQL injection attempts
- I use TABLOCK to encourage a parallel plan on insert