开发者

Declare variable in table valued function

开发者 https://www.devze.com 2023-03-19 20:28 出处:网络
How can I declare a variable in a table valued function? (like in my ti开发者_开发百科tle)There are two flavors of table valued functions. One that is just a select statement and one that can have mor

How can I declare a variable in a table valued function? (like in my ti开发者_开发百科tle)


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


In SQL Server:

It's not a very nice solution, but if you have a valid reason for needing to use an inline TVF instead of a MSTVF and cannot pass the variable into the TVF as a parameter, but can obtain it using a SELECT statement, you can use a CTE to access the value as follows:

CREATE FUNCTION func()
RETURNS TABLE
AS 
RETURN
(
-- Create a CTE table containing just the required value
WITH cte_myVar AS
   (SELECT <statement to select variable>) col1

-- Use the value by selecting it from the CTE table
SELECT * FROM table1 t1
WHERE t1.col1 = (SELECT col1 FROM cte_myVar)

)


0

精彩评论

暂无评论...
验证码 换一张
取 消