I have a UDF that takes a table as a parameter (a 2 column table) and outputs a string, much like this article. I have a table that I want to apply the UDF over multiple columns like this:
Date Unit Line Revenue Orders
4/1/12 D R 20.00 3
4/2/12 D R 25.00 4
4/1/12 H W 33.00 1
4/2/12 H W 35.00 3
I want to call my UDF on every row of this table that has the most current date and pass the UDF a table with the columns Date and Revenue for each distinct Unit and Line. And I also want to call the UDF and pass Date and Orders for each distinct Unit and Line. This is a report and the UDF will always get passed the Date column and another column that I want to apply some calculation to and store and report. So I have looked at a lot of things including CROSS APPLY and I want to do something like this:
SELECT T.unit
, T.line
, dbo.fn_myUDF((SELECT T2.Date, T2.Revenue FROM #Table T2)) as UDFRevenueResult
, dbo.fn_myUDF((SELECT T2.Date, T2.Orders FROM #Table T2)) as UDFOrderResult
FROM #Table T
WHERE T.Date = @ReportDate
This gives me the error "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." I looked at CROSS APPLY but that seems only apply for when you are returning a table variable. So I could probably answer my own question by using a cursor and a loop maybe and constructing each table I want to pass to the UDF in each loop iteration but that just doesn't seem right. Can anyone give me an idea how to do what I want in SQL Server 2008?