Delphi: how to pass a list as a parameter to a SQL query?

前端 未结 7 737
你的背包
你的背包 2020-12-17 16:44

I have a list of integers or of strings and need to pass it as a parameter for a Delphi DataSet. How to do it?

Here is an example. MyQuery is something like:

7条回答
  •  时光取名叫无心
    2020-12-17 16:55

    There are several options for you but basically you need to get your values into a table. I would suggest a table variable for that.

    Here is a version that unpacks an int list.

    declare @IDs varchar(max)
    set @IDs = :listParam
    
    set @IDs = @IDs+','
    
    declare @T table(ID int primary key)
    
    while len(@IDs) > 1
    begin
      insert into @T(ID) values (left(@IDs, charindex(',', @IDs)-1))
      set @IDs = stuff(@IDs, 1, charindex(',', @IDs), '')
    end
    
    select *
    from myTable
    where intKey in (select ID from @T)
    

    It is possible to have multi-statement queries. The parameter :listParam should be a string:

    MyQuery.ParamByName('listParam').AsString := '1,2,3';
    

    You can use the same technique for strings. You just need to change the data type of ID to for instance varchar(10).

    Instead of unpacking with a while loop you could make use of a split function

    declare @T table(ID varchar(10))
    
    insert into @T 
    select s
    from dbo.Split(',', :listParam)
    
    select *
    from myTable
    where  charKey in (select ID from @T)
    

    A string param could look like this:

    MyQuery.ParamByName('listParam').AsString := 'Adam,Bertil,Caesar';
    

提交回复
热议问题