如何在用户定义函数中使用临时表

问题描述 投票:0回答:2

我正在创建一个函数并将结果存储在#temp 表中。我收到与 #temp 表相关的错误,尽管它们位于函数之外,并且出现与错误语法相关的错误,我无法更正源代码。

我的SQL片段:

create function dbo.function1 (@datet int)
returns table 
as return (
    select field1, 'TRUE' as 'Y/N'
    from table1 t1 with (nolock)    
        join table2 t2 with (nolock) on t1.id = t2.id
            and field4 = @datet
    group by field1
    having sum (case when t1.field3 in (1,2,7) and t2.field4 ='YES' then t1.value1 else 0 end) <> 0
) go ;


declare @s_date as int = 20231130   
declare @e_date as int = 20231206

select * into #temp1 from (select * from dbo.function1 (@s_date))
select * into #temp2 from (select * from dbo.function1 (@e_date))

drop table #temp1, #temp2

我的错误:

Cannot access temporary tables from within a function.
Procedure function1, Line 21 [Batch Start Line 0]
Incorrect syntax near ';'.
Procedure function1, Line 22 [Batch Start Line 0]
Cannot access temporary tables from within a function.
Procedure function1, Line 22 [Batch Start Line 0]
Incorrect syntax near ';'.
Procedure function1, Line 24 [Batch Start Line 0]
Cannot access temporary tables from within a function.
Procedure function1, Line 24 [Batch Start Line 0]
Cannot access temporary tables from within a function.
sql sql-server sql-function
2个回答
0
投票

不幸的是,SQL Server UDF 无法访问临时表 - 请参阅 https://learn.microsoft.com/en-us/sql/relational-databases/user-definition-functions/create-user- 中的“限制和限制”定义功能数据库引擎。根据您的情况,您也许可以使用表变量。 关于语法错误,我认为您不能在一个语句中删除多个表(如果您删除临时表,它将不相关)。另外,我相信您需要通过在末尾添加别名来调整最后两个选择,如下所示:

select * into #temp1 from (select * from dbo.function1 (@s_date)) src
select * into #temp2 from (select * from dbo.function1 (@e_date)) src

0
投票

您可以使用带有

insert into
的存储过程来代替函数:

create procedure proc1 (@datet int)
as
begin

select field1, 'TRUE' as 'Y/N'
from table1 t1 with (nolock)    
  join table2 t2 with (nolock) on t1.id = t2.id and field4 = @datet
group by field1
having sum (
  case when t1.field3 in (1,2,7) and t2.field4 ='YES' 
    then t1.value1 
    else 0 
  end) <> 0

end 
go

create table #temp1 (
field1 int,
yes_no varchar(10)
)
go
create table #temp2 (
field1 int,
yes_no varchar(10)
)
go


declare @s_date as int = 20231130   
declare @e_date as int = 20231206

insert into #temp1 exec proc1 @s_date
insert into #temp2 exec proc1 @e_date
go
drop table #temp1
go
drop table #temp2
go
© www.soinside.com 2019 - 2024. All rights reserved.