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
Local and global temporary tables play a vital role in the SQL Server scripting. We generally use it to store temporary values for further manipulation. But unfortunately, you cannot use it inside the user defined function.
In addition, it is also perfectly valid to use Common Table Expression (CTE) in ITVF. ); Note that ITVF cannot have BEGIN and END block encapsulating the RETURN statement. You will get error “Incorrect syntax near BEGIN” when use BEGIN and END statement as follow.
This biggest difference is that a CTE can only be used in the current query scope whereas a temporary table or table variable can exist for the entire duration of the session allowing you to perform many different DML operations against them.
A TEMP Table of User Defined Table Type has to be created of the same schema as that of the Table Valued parameter and then it is passed as Parameter to the Stored Procedure in SQL Server.
You can use a table variable instead.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With