How to pass an array into a SQL Server stored procedure

前端 未结 11 2439
轻奢々
轻奢々 2020-11-21 23:28

How to pass an array into a SQL Server stored procedure?

For example, I have a list of employees. I want to use this list as a table and join it with another table.

11条回答
  •  臣服心动
    2020-11-22 00:00

    You need to pass it as an XML parameter.

    Edit: quick code from my project to give you an idea:

    CREATE PROCEDURE [dbo].[GetArrivalsReport]
        @DateTimeFrom AS DATETIME,
        @DateTimeTo AS DATETIME,
        @HostIds AS XML(xsdArrayOfULong)
    AS
    BEGIN
        DECLARE @hosts TABLE (HostId BIGINT)
    
        INSERT INTO @hosts
            SELECT arrayOfUlong.HostId.value('.','bigint') data
            FROM @HostIds.nodes('/arrayOfUlong/u') as arrayOfUlong(HostId)
    

    Then you can use the temp table to join with your tables. We defined arrayOfUlong as a built in XML schema to maintain data integrity, but you don't have to do that. I'd recommend using it so here's a quick code for to make sure you always get an XML with longs.

    IF NOT EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'xsdArrayOfULong')
    BEGIN
        CREATE XML SCHEMA COLLECTION [dbo].[xsdArrayOfULong]
        AS N'
        
            
                
                    
                
            
        
    ';
    END
    GO
    

提交回复
热议问题