Click here to Skip to main content
15,885,188 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I want to store data into temporary table from exec sp_executesql @query statement
but i am not able to do that.

What I have tried:

SQL
set @query1 = N'SELECT  EmployeeCode, ' + @cols + N' from 
             (
                select EmployeeCode, activity,Actual
                from #target1
            ) x
            pivot 
            (
                max(Actual)
                for activity in (' + @cols + N')
            ) p '

select * into #temp from 
exec sp_executesql @query;


I got Error in last line incorrect syntax
Posted
Updated 15-Mar-16 19:06pm
v3
Comments
dan!sh 15-Mar-16 8:26am    
This will not work. If you can update the question with what you are trying to do, someone can suggest a better approach. Also, since you already have the query ready, why are you even using sp_executesql?
CHill60 15-Mar-16 12:57pm    
Why use sp_excutesql ... because if OP puts "exec @query" they will get the error "Could not find stored procedure '...."
Of course if they use the correct syntax it will work ... exec (@query)
dan!sh 15-Mar-16 13:40pm    
You must be joking. There is no need for executing dynamic queries here.
CHill60 15-Mar-16 18:54pm    
How else can the OP generate the list of columns for the pivot? If not dynamic query then it would have to be a hard-coded list ... which implies knowing the data beforehand.
Dynamic queries are quite common for pivot situations like this

Try:
SQL
CREATE TABLE #tempTable(Column1 INT, Column2 UNIQUEIDENTIFIER, Column3 DATE)
INSERT INTO #tempTable(Column1, Column2, Column3)
   EXEC sp_executesql @query
SELECT * FROM #tempTable
DROP TABLE #tempTable
Or better, replace your SP with a table valued function.
 
Share this answer
 
SQL
CREATE TABLE #tempTable(id int);

sp_executesql 'INSERT INTO #tempTable SELECT myId FROM myTable';

SELECT * FROM #tempTable;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900