Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute sp_executeSql for select...into #table but Can't Select out Temp Table Data

Was trying to select...into a temp Table #TempTable in sp_Executedsql. Not its successfully inserted or not but there Messages there written (359 row(s) affected) that mean successful inserted? Script below

DECLARE @Sql NVARCHAR(MAX); SET @Sql = 'select distinct Coloum1,Coloum2 into #TempTable              from SPCTable with(nolock)             where Convert(varchar(10), Date_Tm, 120) Between @Date_From And @Date_To';  SET @Sql = 'DECLARE @Date_From VARCHAR(10);             DECLARE @Date_To VARCHAR(10);             SET @Date_From = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';             SET @Date_To = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';             '+ @Sql;  EXECUTE sp_executesql @Sql; 

After executed,its return me on messages (359 row(s) affected). Next when trying to select out the data from #TempTable.

Select * From #TempTable; 

Its return me:

Msg 208, Level 16, State 0, Line 2 Invalid object name '#TempTable'. 

Suspected its working only the 'select' section only. The insert is not working. how fix it?

like image 641
Worgon Avatar asked Nov 07 '11 17:11

Worgon


People also ask

What is execute Sp_executesql?

The sp_executesql is a built-in stored procedure in SQL Server that enables to execute of the dynamically constructed SQL statements or batches. Executing the dynamically constructed SQL batches is a technique used to overcome different issues in SQL programming sometimes.

What is the difference between execute and Sp_executesql?

sp_executesql supports parameterisation, whereas EXEC only accepts a string. Only performance differences that may arise are due to the parameterisation i.e. a parameterised sp_executesql call is more likely to have a reusable cached plan.

Can we use Sp_executesql in function?

It appears that you can't. You can execute extended stored procedure inside a function and, even though sp_executesql is an extended stored procedure (despite its name), it still generates the message "only functions and extended stored procedures can be executed within a function".


1 Answers

Using a global temporary table in this scenario could cause problems as the table would exist between sessions and may result in some problems using the calling code asynchronously.

A local temporary table can be used if it defined before calling sp_executesql e.g.

CREATE TABLE #tempTable(id int);  sp_executesql 'INSERT INTO #tempTable SELECT myId FROM myTable';  SELECT * FROM #tempTable; 
like image 72
Rob Willis Avatar answered Sep 24 '22 08:09

Rob Willis