-1

I would like to do create a SQL function like this (pseudocode):

function PeopleInCompanies(companyIds)
   SELECT * from Person WHERE CompanyId IN (companyIds)
end function

and call it like this:

define companyIds = 1,2,3
select * from PeopleInCompanies(companyIds)

is it even possible?

Dale K
  • 21,987
  • 13
  • 41
  • 69
Luke
  • 113
  • 1
  • 7

2 Answers2

0

You would need to use a table type parameter. Assuming that CompanyID is an int:

CREATE TYPE dbo.ints AS TABLE ([value] int);
GO

CREATE FUNCTION dbo.PeopleInCompanies (@CompanyID dbo.ints READONLY)
RETURNS TABLE
AS RETURN

    SELECT P.* --This should be replaced by the columns you need.
    FROM dbo.Person P
         JOIN @CompanyID CI ON P.CompanyID = CI.[Value];

Then you would call the function using:

DECLARE @CompanyID dbo.ints;
INSERT INTO @CompanyID
VALUES (1),(2),(3);

SELECT *
FROM dbo.PeopleInCompanies(@CompanyID);
Larnu
  • 76,706
  • 10
  • 34
  • 63
0

SQL Server does not support macro substitution. That said, you have the table type as Gordon and Larnu mentioned, or you can simply parse/split the delimited string

Just another option

Declare @companyIds varchar(max) = '1,2,3'

Select A.*
  From Person A
  Join string_split(@companyIds,',') B 
    on A.CompanyID = B.Value
John Cappelletti
  • 71,300
  • 6
  • 42
  • 62