-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
  • 25,246
  • 15
  • 42
  • 71
Luke
  • 194
  • 3
  • 10

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);
Thom A
  • 88,727
  • 11
  • 45
  • 75
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
  • 79,615
  • 7
  • 44
  • 66