简体   繁体   English

C#/ SQL效率查询

[英]C# / SQL Efficiency Query

I've got a Winforms application that connects to a SQL database and retrieves data, the application then needs to check if the data exists in another SQL database before performing an action. 我有一个Winforms应用程序,该应用程序连接到SQL数据库并检索数据,然后该应用程序需要在执行操作之前检查数据是否存在于另一个SQL数据库中。

I've seen similar queries but most tend to be for SQL, what I'd like to know is which of the two options below, is better in terms of overall performance. 我见过类似的查询,但是大多数查询都是针对SQL的,我想知道的是以下两个选项中的哪一个在整体性能方面更好。 I've considered two approaches: 我考虑了两种方法:

1.Create two lists in C#, populate them and then check if the value from the first list exists in the next list: 1.在C#中创建两个列表,填充它们,然后检查第一个列表中的值是否存在于下一个列表中:

List<T> firstList = new List<T>();
List<X> secondList = new List<X>();

firstList = firstList.populate(); // SQL Stored Procedure to populate list
secondList = secondList.populate(); // SQL Stored Procedure to populate list 

foreach(var item in firstList)
{
  if( (x => x.value == item.value) )
  {
     //do some action
  }
}

2.Create a list in C# and a method that executes a Stored Procedure to check if a value passed as a parameter exists in the SQL database. 2.在C#中创建一个列表,并创建一个执行存储过程的方法,以检查SQL数据库中是否存在作为参数传递的值。 Once the list is populated I would iterate through it and execute the new method returning a boolean value: 填充列表后,我将遍历列表并执行返回布尔值的新方法:

List<T> firstList = new List<T>();

firstList = firstList.populate();  // SQL Stored Procedure to populate list

foreach(var item in firstList)
{
  bool exists = false;
  exists = firstList.checkValue(item.value);  // SQL Stored Procedure to check if value exists
  if(exists)
  {
     //do some action
  }
}

I'm not sure whether it's better to perform many SQL queries and reduce memory usage or perform fewer queries and use memory. 我不确定执行许多SQL查询并减少内存使用量还是执行较少的查询并使用内存是更好的选择。 This application will run on a small application server which should have 32Gb RAM. 此应用程序将在应具有32Gb RAM的小型应用程序服务器上运行。

I'm also open to using another technique if either of my approaches aren't efficient. 如果我的两种方法都不有效,我也愿意使用另一种技术。

I would suggest it would be more efficient to run the whole query on the SQL server. 我建议在SQL Server上运行整个查询会更有效。 Retrieving any data from a remote database and doing a comparison locally would never be quicker than doing that comparison where the source of the data is held. 从远程数据库检索任何数据并在本地进行比较永远不会比在保存数据源的地方进行比较更快。

My suggestion would be to write an SPROC that does the comparison and returns only the rows that exist in both databases. 我的建议是编写一个进行比较并仅返回两个数据库中都存在的行的SPROC。

Possibly use something like: 可能使用类似:

SELECT
    *
FROM
    [SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]

Or have a look at linked tables in Sql Server 或看看Sql Server中的链接表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM