Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple values to a parameter of a function in SQL

There is function Getfunctionname(userid, startdate, enddate) to return a table

My question is can I pass a variable with multiple values?

i.e.

getfunctionname(@userid, startdate, enddate)

Where the value of variable @userid is like

1
2
3
4
5

(actually using split function splitting the values from being 1,2,3,4,5 )

If I can please let me know

like image 317
Aswin Avatar asked Oct 19 '22 23:10

Aswin


2 Answers

One way of doing that which I prefer is to make a new user-defined table data type.

CREATE TYPE [dbo].[IdList] AS TABLE(
    [Id] [int] NULL
)

Then you can use that data type as one of the parameters

CREATE FUNCTION Getfunctionname
(   
    @UserIDs dbo.IdList READONLY,
    @startdate INT,
    @endtdate INT
     )
RETURNS @ReturnTable TABLE                                        
   (                                        
     -- ReturnTable
   )
AS
BEGIN
  -- Query    
RETURN

END
like image 100
sqluser Avatar answered Nov 03 '22 04:11

sqluser


Use the concept of CSV

CREATE FUNCTION [dbo].[uspGetNumbers]
    userid,startdate,enddate // define your paramters the way you want
AS
BEGIN
// your code
JOIN dbo.fnSplit(@UserIDs, ',') 
END
GO

Example function:

SELECT [dbo].[uspGetNumbers] '1,2,3,4,5', '', ''
like image 37
MusicLovingIndianGirl Avatar answered Nov 03 '22 03:11

MusicLovingIndianGirl