Share via

SQL Server Table valued functions

Mohammed Arshad Alikhan 86 Reputation points
2022-05-06T14:15:35.537+00:00

Hi there, I am learning T-SQL Table valued functions and would need some help.

The body of the table valued functions start with the return and then the select statement .

Eg: - CREATE FUNCTION udfProductInYear (@model_year INT) RETURNS TABLE AS RETURN SELECT product_name,model_year,list_price FROM production.products WHERE model_year = @model_year

But if I want to declare a variable and execute some commands and later select records from table then can I be able to do it? something like below

CREATE FUNCTION udfProductInYear (@model_year INT)
RETURNS TABLE AS
Begin 
declare @year=@model_year+2 --increasing the year by 2
RETURN
SELECT product_name,model_year,list_price FROM
production.products WHERE model_year = @year;
end

Thank you

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

  1. Naomi Nosonovsky 8,906 Reputation points
    2022-05-06T14:22:23.62+00:00

    In this case it would not be inline table-valued function, it would be multi-statement table-valued function and its syntax will be

    create function ufn_Something (@默 _year int)
    return @Result table (....) -- definition of the table variable here
    as
    begin
    ....
    ....
    insert into @Result (...)
    select ....

    return;
    end

    Was this answer helpful?

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.