gpt4 book ai didi

sql-server-2008 - 在表值函数中使用临时表

转载 作者:行者123 更新时间:2023-12-03 12:40:17 25 4
gpt4 key购买 nike

我正在尝试在一个表值函数中使用一个临时表,但看来我做不到。我还有其他方法可以在表值函数中使用临时表吗?
当前代码:

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

最佳答案

您可以改用table variable

DECLARE @Child TABLE (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))
DECLARE @Parent TABLE (Id INT, Name VARCHAR(255), ParentId INT, ParentName VARCHAR(255))

关于sql-server-2008 - 在表值函数中使用临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7980807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com