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
0 comments No comments
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,431 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

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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