Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have temp tables in a function?

Tags:

Apparently, I can't use them. I'm getting an error message like:

Invalid use of a side-effecting operator 'SELECT' within a function

If I want to do something like this:

select bleh   into #temp   from Blah 

... inside a function.

like image 756
aarona Avatar asked Mar 23 '12 18:03

aarona


People also ask

Is it possible to create temp table in function SQL Server?

When we query the TempPersonTable, it will return an empty result set. After creating the table, we can insert data into it as the persisted tables. At the same time, we can create a temporary table using the SQL SELECT INTO statement command.

Can we create a table inside a function?

You can create a table for the duration of the function by declaring it as a variable. We use the following code within a function to determine what date the last occurrence of a certain Cycle was.

Can you have temp tables in a view?

No, a view consists of a single SELECT statement. You cannot create or drop tables in a view. Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.

Can we use temp table in CTE?

You cannot create and drop the #TEMP table within the CTE query.


2 Answers

No, per this thread where the same question was asked, you cannot, but you can use a table variable

DECLARE @MyTempTableVariable TABLE (SCHEMA)  INSERT INTO @MyTempTableVariable SELECT bleh FROM bleh 
like image 146
Justin Pihony Avatar answered Oct 14 '22 07:10

Justin Pihony


You can also do it with a CTE. See the template browser in SSMS. IntelliSense confuses the issue and will show an error until you complete the CTE and the following insert/select, but it will work.

like image 42
Lew Wolf Avatar answered Oct 14 '22 08:10

Lew Wolf