5

I am altering function like:

ALTER FUNCTION [dbo].[fn_CalculateListing](@Listing TypeListingDatePrice READONLY)
RETURNS TypePreviousListingResult 
AS 
BEGIN
 DECLARE @tbl_ListingDateDetails TypePreviousListingResult 
 RETURN @tbl_ListingDateDetails
END
GO

But throwing error as:

Msg 137, Level 16, State 1, Procedure fn_CalculateListing, Line 6
Must declare the scalar variable "@tbl_ListingDateDetails".

Why this giving error and asking for declaration even though I have declared that before using that variable?

TypePreviousListingResult is a table type created as CREATE TYPE TypePreviousListingResult AS TABLE....

Previous question: How to write function in sql which accept table as input and return result back as table?

asked Jan 25, 2016 at 6:00
0

1 Answer 1

11

There are two problems here:

  1. For Multistatement TVFs, you just need RETURN; instead of RETURN @variable;.

  2. It does not appear as though you can use a User-Defined Table Type (UDTT) as the return table type. That will need to be specified explicitly (i.e. each column name and datatype).

If this were a Scalar UDF, then the syntax of specifying only the datatype name in the RETURNS clause, and specifying the variable name in the RETURN statement, would be correct. However, you cannot return TABLE (or CURSOR) types from a Scalar UDF.

Please see the MSDN page for CREATE FUNCTION for more details.

You will need something along the lines of:

ALTER FUNCTION [dbo].[fn_CalculateListing]
(
 @Listing dbo.TypeListingDatePrice READONLY
)
RETURNS @ListingDateDetails TABLE (ColumnName DataType,...)
AS 
BEGIN
 -- Do stuffs
 RETURN;
END;
GO

For a broader discussion of the available techniques to pass sets of rows around, see: How to Share Data between Stored Procedures by Erland Sommarskog.

answered Jan 25, 2016 at 6:19
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.