I'm trying to get a few values from a dynamic SELECT
This is my code:
DECLARE @sqlCommand varchar(1000)
DECLARE @colName varchar(20)
DECLARE @tableName varchar(20)
DECLARE @myNum int
DECLARE @varDate varchar(19)
DECLARE @myTime datetime2
set @varDate = getdate()
SET @colName = 'col1'
SET @tableName = 'table'
SET @sqlCommand = 'SELECT top 1 @myTime=mytime, @myNum=' + @colName + ' FROM ' + @tableName + ' WHERE mytime>=''' + @varDate + ''' ORDER BY mytime'
PRINT @sqlCommand
EXEC(@sqlCommand)
When I print the SQL command, this is what I get:
SELECT top 1 @myTime=mytime, @myNum=col1
FROM table
WHERE mytime>='Jul 25 2017 4:40PM'
ORDER BY mytime
When I try to EXEC
it, I get this error:
Must declare the scalar variable "@myTime".
If I do this:
SET @sqlCommand = 'SELECT top 1 mytime, ' + @colName + ' FROM ' + @tableName + ' WHERE mytime>=''' + @varDate + ''' ORDER BY mytime'
It works well, but I need to use that data.
Thanks in advance.