Define variable to use with IN operator (T-SQL)

后端 未结 14 2074
心在旅途
心在旅途 2020-11-28 04:24

I have a Transact-SQL query that uses the IN operator. Something like this:

select * from myTable where myColumn in (1,2,3,4)

Is there a wa

14条回答
  •  难免孤独
    2020-11-28 04:49

    Use a function like this:

    CREATE function [dbo].[list_to_table] (@list varchar(4000))
    returns @tab table (item varchar(100))
    begin
    
    if CHARINDEX(',',@list) = 0 or CHARINDEX(',',@list) is null
    begin
        insert into @tab (item) values (@list);
        return;
    end
    
    
    declare @c_pos int;
    declare @n_pos int;
    declare @l_pos int;
    
    set @c_pos = 0;
    set @n_pos = CHARINDEX(',',@list,@c_pos);
    
    while @n_pos > 0
    begin
        insert into @tab (item) values (SUBSTRING(@list,@c_pos+1,@n_pos - @c_pos-1));
        set @c_pos = @n_pos;
        set @l_pos = @n_pos;
        set @n_pos = CHARINDEX(',',@list,@c_pos+1);
    end;
    
    insert into @tab (item) values (SUBSTRING(@list,@l_pos+1,4000));
    
    return;
    end;
    

    Instead of using like, you make an inner join with the table returned by the function:

    select * from table_1 where id in ('a','b','c')
    

    becomes

    select * from table_1 a inner join [dbo].[list_to_table] ('a,b,c') b on (a.id = b.item)
    

    In an unindexed 1M record table the second version took about half the time...

    cheers

提交回复
热议问题