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
)
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.
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.
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.
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.....
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]()
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