Thursday, 2 June 2016

SQL Server - Access TEMP table created dynamically


Sql server provides an option to create the query dynamically and execute it as below.

DECLARE @SqlStmt VARCHAR(2000)
SET @SqlStmt='SELECT * FROM HumanResources.Employee'

EXEC (@SqlStmt)












Even temporary table also can be created dynamically as follows.

DECLARE @SqlStmt VARCHAR(2000)
SET @SqlStmt='CREATE TABLE #Class(ID INT, Name VARCHAR(200))'

EXEC (@SqlStmt)

But when you insert or Select statements on #Class table immediately next to above query, Sql Server throws an error “Invalid object name '#Class'.













To Avoid that you have to write insert/select statements also inside dynamic query string.
As #Class temporary table created dynamically that ends it's scope after EXEC statement. So you should write any further queries inside dynamic query string itself.