Link to home
Start Free TrialLog in
Avatar of Harreni
HarreniFlag for Saudi Arabia

asked on

Ordering data descending in Table Valued Function

Hi Experts,

I have this table Valued Function and I tried to order the returned records descending but without success.
so is there any way to achieve it?

/* Create a table type. */
CREATE TYPE CusResults AS TABLE 
( 
  ConsumerID	NVARCHAR(50) NULL 
);
GO

/* Create a procedure to receive data for the table-valued parameter. */
CREATE PROCEDURE dbo. SP_RecivedDataForTBV @TVP CusResults READONLY
AS 
SET NOCOUNT ON

SELECT 
C.ConsumerID
, C.ConsumerName
, C.CurrentlyConsumer
, COUNT(distinct DSI.ServiceID) #OfServicesNeedsDatasest
, COUNT(distinct DSI.DatasetID) #OfRequiredDatasest
FROM Consumers C
	INNER JOIN Services S ON C.ConsumerID = S.ConsumerID
	INNER JOIN Datasets_Services_Intersection DSI ON S.ServiceID = DSI.ServiceID
	INNER JOIN Datasets DS ON DSI.DatasetID = DS.DatasetID
Where C.ConsumerID in (select ConsumerID from @TVP) and DS.ShowInResult=1 
GROUP BY C.ConsumerID, C.ConsumerName, C.CurrentlyConsumer

/* Declare a variable that references the type. */
DECLARE @CusResults AS CusResults;

/* Add data to the table variable. */
--INSERT INTO @CusResults (
ConsumerID
,ConsumerName
, CurrentlyConsumer
, NumberOfService
, NumberOfDatasets)
INSERT INTO @CusResults (ConsumerID)
SELECT top 1000 C.ConsumerID
FROM Consumers C

/* Pass the table variable data to a stored procedure. */
EXEC SP_RecivedDataForTBV @CusResults;
GO

Open in new window

Thanks in advance.
Harreni
SOLUTION
Avatar of crystal (strive4peace) - Microsoft MVP, Access
crystal (strive4peace) - Microsoft MVP, Access

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Harreni

ASKER

Thanks a lot Crystal for your help and Eric for this explanation "I understood previously, that this is a TVF".
It works fine.
A TVF is a function as shown in https://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx.

What you have is a stored procedure using a TVP (Table Value Parameter).
Avatar of crystal (strive4peace) - Microsoft MVP, Access
crystal (strive4peace) - Microsoft MVP, Access

you're welcome, Harreni ~ happy to help