问题描述
我试图按照我的要求创建一个功能。但是,当创建或删除 #tempTable
时,它会给出错误:
我的理解是我们不能有 create
, drop
或在函数中对
操作。 #temptable
插入
是否正确?
My SQL:
CREATE FUNCTION [dbo]。[RT_ResultFunction ]
(
Id VARCHAR(4000)
)
RETURNS @RT_ResultFunction TABLE
(
Id VARCHAR(20)
,Name varchar 20)
,Balance Int
)
AS
BEGIN
IF OBJECT_ID('tempdb ..#tempTable')不为空
DROP TABLE #tempTable
SELECT ID,COUNT(余额)
INTO #tempTable
'余额'FROM Table1
INSERT @RT_ResultFunction
SELECT T1.ID ,T1,NAME,T2,Balance
FROM Table2 T1,
#tempTable T2
WHERE T1.ID = T2.ID
RETURN
END
这是正确的 - 您不能产生副作用: / p>
从这里开始:
你会发现,即使没有你的 DROP
语句,是任何访问临时表的尝试都会给你消息(比如 SELECT ... INTO #TMP
):
$ b
As @Dems指出,你可以使用表变量。因为这些都是变量,所以它们被限制在函数中,因此不会产生副作用。
您的函数可以运行为:
...
BEGIN
DECLARE @tempTable表(id varchar(20),rows int)
insert @tempTable
SELECT ID,COUNT(余额)
FROM Table1
INSERT @RT_ResultFunction
SELECT T1.ID,T1,NAME,T2,Balance
FROM Table2 T1,
@tempTable T2
WHERE T1.ID = T2.ID
RETURN END
未经测试或任何其他事物,但您获得了要点。
I am trying to create a function as per my requirements.
But, when am creating or drop #tempTable
, it is giving an error as:
My understanding is that we can't have create
, drop
or insert
operations on #temptable
in a function.
Is that correct?
My SQL:
CREATE FUNCTION [dbo].[RT_ResultFunction]
(
Id VARCHAR(4000)
)
RETURNS @RT_ResultFunction TABLE
(
Id VARCHAR(20)
, Name varchar(20)
,Balance Int
)
AS
BEGIN
IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
DROP TABLE #tempTable
SELECT Id, COUNT(Balance)
INTO #tempTable
'Balance' FROM Table1
INSERT @RT_ResultFunction
SELECT T1.ID,T1,NAME,T2,Balance
FROM Table2 T1,
#tempTable T2
WHERE T1.ID = T2.ID
RETURN
END
That is correct - you cannot have side effecting statements:
From here: http://msdn.microsoft.com/en-us/library/aa175085(v=sql.80).aspx
What you would find, even without your DROP
statement, is that any attempt to access a temp table will give you the message (such as a SELECT ... INTO #TMP
):
As @Dems points out, you can use table variables. Because these are variables, they are scoped within the function, and therefore aren't side effecting.
Your function might run as:
...
BEGIN
DECLARE @tempTable table (id varchar(20), rows int)
insert @tempTable
SELECT Id, COUNT(Balance)
FROM Table1
INSERT @RT_ResultFunction
SELECT T1.ID,T1,NAME,T2,Balance
FROM Table2 T1,
@tempTable T2
WHERE T1.ID = T2.ID
RETURN END
Not tested or anything, but you get the gist.
这篇关于创建,删除并在用户定义的函数中插入临时表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!