Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a sql store procedure than runnig in parallel.
The process write to temp table that contain session id in the last
so that each process has its own temp table.

example
SQL
##temp_table + CONVERT(varchar(10),(select @@SPID)) 

The tables that created

##temp_table_121
##temp_table_122


The problem

I need to select data from these tables in function.
But in function I can't use dynamic sql.

How can I use these tables in function?

What I have tried:

Using dynamic sql in function - I gen an error
Posted
Updated 10-Sep-16 20:22pm
Comments
Herman<T>.Instance 8-Sep-16 5:44am    
Add brackets [] around it like:
[##temp_table_121]
[##temp_table_122]
Member 8092498 8-Sep-16 5:56am    
I don't know the name of the tables.
I retreive it by using ##temp_table + CONVERT(varchar(10),(select @@SPID))
so it's dynamic
PeejayAdams 8-Sep-16 6:05am    
It simply can't be done in a UDF. You could try using a CLR function.
Member 8092498 8-Sep-16 6:52am    
What is CLR function?
Karthik_Mahalingam 9-Sep-16 1:24am    
udf ?

Based on what i think you are trying to do, you need to use exec sp_executesql. Here is an example.

SQL
IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL DROP TABLE #MyTempTable
		CREATE TABLE #MyTempTable
		(
			Id INT NULL
		)

DECLARE @TableName VARCHAR(200) = '#MyTempTable';

DECLARE @Sql NVARCHAR(500) = 'SELECT * FROM ' + @TableName;


EXEC sp_executesql @Sql
 
Share this answer
 
v2
Comments
Member 8092498 11-Sep-16 1:40am    
I can't use sp_executesql in sql function..
My solution:
I have created a SQL table type.
In the store procedure than run the function I have declared an object of this type, insert the temp table data to this object and passed it to the function.
 
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