在表值函数中使用临时表
我试图在表值函数中使用临时表,但似乎不能。有没有其他方法可以在表值函数中使用临时表?
当前代码:
CREATE FUNCTION dbo.fnt_AllChildren (@ParentName VARCHAR(255))
RETURNS @return_variable TABLE
(
Id INT,
Name VARCHAR(255),
ParentId INT,
ParentName VARCHAR(255)
)
AS
BEGIN
CREATE TABLE #Child (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))
CREATE TABLE #Parent (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))
INSERT #Child (Id, Name, ParentId, ParentName)
SELECT child.Id, child.Name, child.ParentId, parent.Name
FROM dbo.t_mytable child
INNER JOIN dbo.t_mytable parent ON child.ParentId = parent.Id
WHERE parent.Name = @ParentName
WHILE (@@ROWCOUNT > 0)
BEGIN
INSERT INTO @return_variable
SELECT * FROM #Child
DELETE FROM#Parent
INSERT INTO #Parent
SELECT * FROM #Child
DELETE FROM #Child
INSERT INTO #Child (Id, Name, ParentId, ParentName)
SELECT child.Id, child.Name, child.ParentId, parent.Name
FROM dbo.t_mytable child
INNER JOIN #Parent parent ON child.ParentId = parent.Id
END
RETURN
END
GO
I'm trying to use a temp table in a table-valued function, but it seems I can not. Is there any other way I can use a temp table in a table-valued function?
CURRENT CODE:
CREATE FUNCTION dbo.fnt_AllChildren (@ParentName VARCHAR(255))
RETURNS @return_variable TABLE
(
Id INT,
Name VARCHAR(255),
ParentId INT,
ParentName VARCHAR(255)
)
AS
BEGIN
CREATE TABLE #Child (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))
CREATE TABLE #Parent (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))
INSERT #Child (Id, Name, ParentId, ParentName)
SELECT child.Id, child.Name, child.ParentId, parent.Name
FROM dbo.t_mytable child
INNER JOIN dbo.t_mytable parent ON child.ParentId = parent.Id
WHERE parent.Name = @ParentName
WHILE (@@ROWCOUNT > 0)
BEGIN
INSERT INTO @return_variable
SELECT * FROM #Child
DELETE FROM#Parent
INSERT INTO #Parent
SELECT * FROM #Child
DELETE FROM #Child
INSERT INTO #Child (Id, Name, ParentId, ParentName)
SELECT child.Id, child.Name, child.ParentId, parent.Name
FROM dbo.t_mytable child
INNER JOIN #Parent parent ON child.ParentId = parent.Id
END
RETURN
END
GO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以改用表变量。
You can use a table variable instead.
不,
您可以使用
@table_variables
。尽管快速浏览一下,递归 CTE 可能更适合您根本不使用这些子/父表。No.
You can use
@table_variables
though. Although from a quick glance maybe a recursive CTE might work for you rather than using these child/parent tables at all.