SQL Server 在表值函数中声明变量

whhtz7ly  于 2023-02-11  发布在  其他
关注(0)|答案(2)|浏览(209)

如何在表值函数中声明变量?(如我的标题)

rqenqsqc

rqenqsqc1#

有两种类型的表值函数,一种只是一个select语句,另一种可以包含比select语句更多的行。
这不能有变量:

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

你必须这样做:

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

voj3qocg2#

在SQL Server中:
这不是一个很好的解决方案,但是如果您有正当的理由需要使用内联TVF而不是MSTVF,并且无法将变量作为参数传递到TVF中,但可以使用SELECT语句获得它,则可以使用CTE访问该值,如下所示:

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)

)

相关问题