如何使用数组过滤器填充.NET数据集?

时间:2013-08-01 12:59:41

标签: c# .net dataset

我想使用条件数组的过滤器填充.NET数据集。加载后,数据集太大,无法加载和过滤。在C#中,填充看起来像:

List<int> customerIDs;
...
myAdapter.FillByCustomerIDs(customerIDs);

哪会产生SQL子句

  WHERE CustomerID IN (x,x,x)

其中x,x,x来自customerIDs数组。

我找不到任何方法将这种类型的过滤器传递给TableAdapter查询配置向导。

1 个答案:

答案 0 :(得分:1)

在SQL中创建一个函数(请注意,@s参数的长度为1024,您可能希望增加该值:

CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(1024))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT 
        CAST(SUBSTRING(@s, start, 
            CASE 
                WHEN stop > 0 THEN stop-start 
                ELSE 512 
            END) as int) AS s
    FROM Pieces
  )
  GO

和存储过程:

CREATE PROCEDURE [dbo].[GetCustomerIds]
    @ids nvarchar(max),
    @sep char(1)
AS
    SELECT * 
    FROM Customers 
    WHERE CustomerId in 
        (SELECT s FROM dbo.Split(@sep,@ids))
RETURN 0

TableAdapter查询配置向导中,将FillByCustomerIds命令绑定到上述存储过程。现在,您可能有以下用法:

List<int> customerIDs = new List<int>() { 1, 2, 3, 4 };
myAdapter
    .FillByCustomerIds(dt, 
    customerIDs.Aggregate<int, string>("", 
        (s, i) => s + i.ToString() + ","), ",");