Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in table valued function

People also ask

Can I DECLARE variable in function SQL?

Declaring a Transact-SQL VariableThe DECLARE statement initializes a Transact-SQL variable by: Assigning a name. The name must have a single @ as the first character. Assigning a system-supplied or user-defined data type and a length.


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