1

Is there a possibility to create a SQL Server function with arrays as parameters, to use it as an IN condition?

CREATE FUNCTION NAME
    (@IDLIST ARRAY<varchar(32)>
    )
... 

    RETURN 
        SELECT ID, NAME, DESCRIPTION 
        FROM TABLE_XYZ 
        WHERE ID IN @IDLIST
4
  • 4
    SQL Server doesn't have array types, no. It does have table TYPEs though. Creating a user-defined table type Commented Feb 3, 2022 at 14:43
  • 1
    Does this answer your question? Can we have array type data in sql server 2008 Commented Feb 3, 2022 at 14:55
  • 1
    There's a really good series of articles on precisely this topic. Table-valued parameters are one popular solution, but there are others. Commented Feb 3, 2022 at 14:55
  • What exactly are you trying to achieve? Perhaps you can just CROSS APPLY the function with a single ID? Commented Feb 3, 2022 at 17:33

1 Answer 1

1

SQL Server doesn't support array types, but you can pass through a table variable using Table Types.

However, I don't think you need this here. You can just use a scalar parameter, and CROSS APPLY the function for each row of the outer table.

CREATE OR ALTER FUNCTION dbo.NAME
    (@ID varchar(32))
RETURNS TABLE
AS RETURN 
   SELECT ID, NAME, DESCRIPTION 
   FROM TABLE_XYZ 
   WHERE ID = @ID;
GO
SELECT t.*, n.*
FROM OtherTable t
CROSS APPLY dbo.NAME (t.ID) n;

You can also do this against a table variable or a temp table.

Alternatively, if you have a hard-codeed list you can use a VALUES clause

SELECT t.*, n.*
FROM (VALUES
  ('a'),
  ('b')
) t(ID)
CROSS APPLY dbo.NAME (t.ID) n;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.