创建可搜索的客户数据库时需要考虑的事项?

时间:2016-02-19 11:39:19

标签: c# sql-server indexing

我们公司目前拥有大量独立的客户数据库,这些数据库已存在多年,用于不同的目的。在线销售,商店销售,营销,财务等等。列表继续。大概有10个不同的数据库。

我的任务是创建一个新的" SINGLE"数据库,将旧数据库与新数据库同步并开发API,以便我们可以修改其他产品以连接到新数据库。

我需要的一个关键功能是可以高效搜索数据库。由于我们加入了大量的数据库,因此会有很多客户。

让我们假设Customer表包含此信息。

[CustomerID]    [bigint] IDENTITY(1,1) NOT NULL,
[Title]         [nchar](20)            NULL,
[FirstName]     [nchar](50)            NOT NULL,
[MiddleName]    [nchar](50)            NULL,
[LastName]      [nchar](50)            NOT NULL,
[Alias]         [nchar](100)           NULL,
[DateOfBirth]   [date]                 NULL,
[Gender]        [char](1)              NULL

我在想我会有一个SearchParameters对象,该对象将被传递给我的API并基于此构建一个where子句。

public class SearchParameters
{
    public long?     CustomerID  {get;set;}
    public string    Title       {get;set;}
    public string    FirstName   {get;set;}
    public string    MiddleName  {get;set;}
    public string    LastName    {get;set;}
    public string    Alias       {get;set;}
    public DateTime? DateOfBirth {get;set;}
    public char?     CustomerID  {get;set;}
}

WHERE将是:

SELECT * FROM Customers
WHERE 
  (@CustomerID IS NULL OR CustomerID = @CustomerID)
  AND (@Title IS NULL OR Title = @Title)
  AND .... and so on

这是一个好方法吗?

在索引我的客户表时,我还应该考虑什么。

2 个答案:

答案 0 :(得分:0)

"这是一个好方法吗?" 就个人而言,我不这么认为。您最终会构建可能效率不高的大型查询,完全匹配也会起作用并使用索引,但如果您开始使用部分匹配,则一切都会变慢。

为什么不查看为搜索而构建的工具,例如full text search?

答案 1 :(得分:0)

恕我直言,你需要重新设计你的结构以提高效率。比如nvarchar而不是char(因为这也会影响查询)。您可能在xml字段中拥有多个手机等(AdventureWorks具有示例架构和字段)。

对于搜索,因为这也是一个C#问题,那么在C#端做什么呢?像这样的东西(Northwind作为样本):

void Main()
{
  string country = ""; //"Brazil"
  string city = ""; //"Sao Paulo"
  DateTime? orderDate = null; //new DateTime(1996,8,28);

  var data = db.Orders
    .Where (c => string.IsNullOrEmpty(country) || c.ShipCountry.StartsWith(country) )
    .Where (c => string.IsNullOrEmpty(city) || c.ShipCity.StartsWith(city) )
    .Where (c => orderDate == null || c.OrderDate == orderDate);

}

这有效地与Linq To SQL一起使用并且生成的SQL已经过优化(即:如果值为null,则不会添加国家/地区搜索)。

第二种方法,基于参数构建渐进式查询,除了Linq To SQL之外,还可以使用Linq To EF:

void Main()
{
  string country = ""; //"Brazil"
  string city = ""; //"Sao Paulo"
  DateTime? orderDate = null;//new DateTime(1996,8,28);

  var data = Orders.AsQueryable();

  if (!string.IsNullOrEmpty(country))
  {
    data = data.Where(c => c.ShipCountry.StartsWith(country));
  }
  if (!string.IsNullOrEmpty(city))
  {
    data = data.Where(c => c.ShipCity.StartsWith(city));
  }
  if (orderDate != null)
  {
    data = data.Where(c => c.OrderDate == orderDate);
  }
}