how to add a value per parameter to a select statement in sql within a simple table-valued function?

1

This is my code and wanted to add a value to a select statement that is passed as parameter for a simple table-valued function. Here is my code:

CREATE FUNCTION NMELHORESFORNECEDORES(@N INT )
RETURNS TABLE 
AS 
RETURN SELECT TOP @N/*da erro nesta variavel*/  IDFornecedor AS FORNECEDOR, Nome,TotalFactura FROM Fornecedores
JOIN Facturas ON Facturas.Fornecedor=Fornecedores.IDFornecedor
ORDER BY Nome DESC

The error in this @N variable in the SELECT statement after the RETURN, I can concatenate the value in any way with the statement. how can I do it ??

    
asked by anonymous 28.04.2016 / 18:13

1 answer

2

It is necessary to put the expression in parentheses.

See Books Online > TOP (Transact-SQL) - link

For example, this code works:

USE AdventureWorks2016CTP3;
GO

CREATE FUNCTION dbo.uf_MelhoresFornecedores
(
    @porcento int
)
RETURNS TABLE
AS
RETURN
(
    SELECT TOP (@porcento) PERCENT V.AccountNumber, V.Name, SUM(H.TotalDue) AS 'Total'
        FROM Purchasing.Vendor AS V
            INNER JOIN Purchasing.PurchaseOrderHeader AS H
                ON H.VendorID = V.BusinessEntityID
        GROUP BY V.AccountNumber, V.Name
        ORDER BY Total DESC
);

To test the function, with 10% for example:

SELECT *
    FROM dbo.uf_MelhoresFornecedores(10);

    
29.04.2016 / 08:03