This is more of a syntax question I’m trying to write a store procedure or function that I can embed into a query such as:
select * from MyBigProcOrFunction
I’m trying to define a tabular function but I do not understand how to do it as I build tmp tables to work out the data before I finally have the return at the endtable. My mark up for my code is:
create function FnGetCompanyIdWithCategories() returns table as return ( select * into a #tempTable from stuff ' etc ' select companyid,Company_MarketSector from #tempTables 'the returning table data )
If I define a function, How do I return it as a table?
You can’t access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:
Edit
Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.
In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let’s look at how you would do this if you were using a UDF
As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you’re not using the secondary temporary table (performance is a complete guess on my part).
If you’re going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you’re indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.