Showing posts with label useage. Show all posts
Showing posts with label useage. Show all posts

Monday, February 20, 2012

Need help with UDF useage. Trying to get away without using cursor.

I have a Function (say X) that takes 2 parameters and returns back a table result of multiple records.

And I have a query (say Q) that return rows of 2 columns that I need to feed Function X.

They way I do it right now is I have a cursor that loops through the result of Query Q
and call Function X as I pass the 2 values the the function.

As Function X return with the result set, I load it into a temporary table.

At the end of the cursor processing, I query the temporary table to return the complete result set.

Is there a way do this without using a cursor?

Here is my Function X top part:

alter FUNCTION ReturnItem
(
@.tableName varchar(50),
@.ItemID int
)
returns @.returnTable table
(
ItemName varchar(50),
ItemValue varchar(50),
[Timestamp] datetime
)

JB..

You want to use the CROSS APPLY capability of SS2k5 to "apply" the rows of one table to a UDF. Here is an example:

CREATE TABLE QuerySource
(
c1 INT,
c2 INT
)

INSERT QuerySource VALUES (1,1)
INSERT QuerySource VALUES (2,3)
INSERT QuerySource VALUES (10,15)
INSERT QuerySource VALUES (16,13)

CREATE FUNCTION ReturnItem
(
@.p1 INT,
@.p2 int
)
returns @.returnTable table
(
AddResult int,
SubtractResult int,
TimesResult int,
DivideResult int
)
AS
BEGIN
INSERT @.returnTable SELECT @.p1+@.p2, @.p1-@.p2,@.p1*@.p2,@.p1/@.p2
RETURN
END

SELECT *
FROM QuerySource qs CROSS APPLY dbo.ReturnItem(qs.c1, qs.c2)

|||Hello. Thank you very much for you help. That is exactly what I wanted to do. I never knew such feature exist. Anyway, I was afraid that when the number of data being passed becomes really big, the cursor will slow things down hence, I have to find this solution.

Thank you again.

JB..