Passing multiple values to a parameter of a function in SQL

有些话、适合烂在心里 提交于 2019-12-06 06:03:11

问题


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


回答1:


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



回答2:


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', '', ''


来源:https://stackoverflow.com/questions/33491873/passing-multiple-values-to-a-parameter-of-a-function-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!