Using “IN” in a WHERE clause where the number of items in the set is very large

前端 未结 10 2388
梦毁少年i
梦毁少年i 2021-02-13 05:30

I have a situation where I need to do an update on a very large set of rows that I can only identify by their ID (since the target records are selected by the user and have noth

10条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 06:23

    There are multiple ways of accommodating a large set of values in a where condition

    1. Using Temp Tables

      Insert the values into a temp table with a single column.

      Create a UNIQUE INDEX on that particular column.

      INNER JOIN the required table with the newly created temp table

    2. Using array-like functionality in SQL Server

      SQL does support an array like functionality

      check this link for full documentation.

    SAMPLE SYNTAX :

    Create TABLE #IDs (id int NOT NULL)
    DECLARE @x varchar(max) = '' 
    DECLARE @xParam XML;
    SELECT @xParam = CAST('' + REPLACE(@x, ',', '') + '' AS XML)
    INSERT into #IDs
    SELECT x.i.value('.','NVARCHAR(100)') as key FROM @xParam .nodes('//i') x(i)
    CREATE UNIQUE INDEX IX_#IDs ON #IDs (ID ASC) 
    

    Query using

    SELECT A.Name, A.Age from Table A 
    

    INNER JOIN #IDs id on id.id = A.Key

提交回复
热议问题