Declare variable in table valued function

Sql ServerFunctionUser Defined-Functions

Sql Server Problem Overview


How can I declare a variable in a table valued function? (like in my title)

Sql Server Solutions


Solution 1 - Sql Server

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionesquareView Question on Stackoverflow
Solution 1 - Sql ServerMikael ErikssonView Answer on Stackoverflow