我正在创建一个函数并将结果存储在#temp 表中。我收到与 #temp 表相关的错误,尽管它们位于函数之外,并且出现与错误语法相关的错误,我无法更正源代码。
我正在使用 Microsoft SQL Management Studio。
我的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 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