Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to join a table valued function and another table with parameters

Tags:

Quick background for those interested,

I have a master detail table(options date), about 20 details for each master record. Our oltp system that is saving the data was doing 21 inserts for each new piece of information we saved. This was killing the server, so I'm trying to get this working by substituting comma separated values for the details table. Everything seems to be working, except I can figure out how to get the details table back. I'm trying to use table valued functions, and it's not quite working.

I'd like to call something like

Select Top 100 * FROM dbo.fn_MarketDataDetails (MarketDataMasterID) mdd INNER JOIN MarketDataMaster mdm on mdm.MarketDataMasterID = mdd.MarketDataMasterID 

Clearly, that just doesn't compile.

I can run

Select Top 100 * FROM dbo.fn_MarketDataDetails (15425) // Assuming 15425 is a valid MarketDataMasterID 

And I get back a table that looks like my old details table.

Is this even possible? Am I making any sense?

like image 608
Jonathan Beerhalter Avatar asked May 26 '10 21:05

Jonathan Beerhalter


People also ask

Can we use table valued function in join in SQL Server?

In this article Because the return type of a table-valued function is Table , you can use a table-valued function anywhere in SQL that you can use a table.

Can we join a function and a table?

SQL Server supports table valued functions, what are functions that return data in the form of tables. JOIN operations in SQL Server are used to join two or more tables. However, JOIN operations cannot be used to join a table with the output of a table valued function. APPLY operators are used for this purpose.

Can we use function with inner join in SQL?

Yes if those are same columns.


1 Answers

The APPLY operator should do the trick:

SELECT *  from MarketDataMaster  cross apply dbo.fn_MarketDataDetails (MarketDataMasterID) 

This essentially calls the function once per row returned from MarketDataMaster. "cross apply" works like an inner join, in that only rows for which data is returned by the function will be returned; use "outer apply" for functionality similar to left outer joins.

like image 72
Philip Kelley Avatar answered Oct 13 '22 06:10

Philip Kelley