Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning table from table-valued function and set that value in temp table

I have a table valued function. Also I have scalar valued function within I have declared a temp table. I want to execute the table valued function inside of scalar valued function and set that value in temp table soemething like this

 **Exec @tempTable=TableValuedFunction**

How could i do this?

Here is the table valued function

ALTER FUNCTION [dbo].[fn_Functiont]()
RETURNS TABLE 
AS
RETURN 
(   
SELECT d.*, b.Name AS Name, ps.Name AS PaymentSystemName, c.UserName AS UserName, c.FirstName AS ClientFirstName, c.LastName AS LastName, c.Number AS DocumentNumber, c.Id
FROM Document AS d
JOIN System AS ps ON d.SystemId = ps.Id
JOIN Client AS c ON c.Id = d.ClientId
LEFT JOIN Shop AS b ON b.Id = d.ShopId
WHERE d.OperationTypeId IN (2, 4, 5) AND c.Type = 1
)
like image 396
So_oP Avatar asked Jan 19 '18 07:01

So_oP


People also ask

Can you use temp tables in table-valued functions?

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.

How do you return a table from a function?

To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ). In the function, we return a query that is a result of a SELECT statement.

What will be the return type of a table-valued function?

A table-valued function returns a single rowset (unlike stored procedures, which can return multiple result shapes). Because the return type of a table-valued function is Table , you can use a table-valued function anywhere in SQL that you can use a table.

How do I return a temp table from a function in SQL Server?

No, you cannot "return" a temp table - you can create that temp table before calling your function, and have your function write data into that temp table. But this has a tendency to get rather messy .... you need to make sure to have the temp table created before calling the function.....


1 Answers

First, you need to have a table variable in which the structure is the same (or depends on your desired columns) in the result of your TVF . Example:

DECLARE @tempTable AS TABLE 
(
   .. columns here ...
)

Then insert the rows return from your TVF into the table variable:

INSERT INTO @tempTable
SELECT * FROM [dbo].[fn_Functiont]()
like image 146
John Woo Avatar answered Oct 26 '22 17:10

John Woo