[英]Linq to SQL bulkupdate from 2 different databases, 2 different tables
您好,我正在使用linq和sql创建一个Windows服务,如果在最近5分钟内表中有更改,则更新一些行,到目前为止,这就是我所拥有的:
using System;
using System.Data.SqlClient;
using System.Linq;
namespace Prueba
{
internal static class Program
{
private static void Main()
{
int tienda = 9;
var conex = new DataClasses1DataContext();
try
{
var source =
new SqlConnection(
"Server=LAPTOP-VCD9V9KH\\SQLEXPRESS;Database=backoffice;User Id=sa; Password=root;");
var destination =
new SqlConnection(
"Server=LAPTOP-VCD9V9KH\\SQLEXPRESS;Database=Corporativo_PRB;User Id=sa; Password=root;");
source.Open();
destination.Open();
source.CreateCommand();
var infoExistenciases = conex.Info_Existencias.Where(x => x.FechAct > DateTime.Now.AddMinutes(-5));
foreach (var x in infoExistenciases)
{
var cmd2 = new SqlCommand(
"update Info_Corp_Existencias set Existencia =" + x.Existencia + " where sku ='" + x.SKU + "'" +
"AND Tienda =" + tienda, destination);
cmd2.ExecuteNonQuery();
}
source.Close();
destination.Close();
Console.Beep();
}
catch
(Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
throw;
}
}
}
}
到目前为止,这段代码将更新目标服务器中的所有内容,但我真的无法真正确定如何将所有内容放入临时表中以让linq更新它的foreach参数。
感谢您的时间
由于它位于两个不同的表中,因此很难在不完全了解表设计的情况下在第二个表中选择相应的行。 但是您可能可以执行以下操作:
var cmd2 = new SqlCommand(
"update Info_Corp_Existencias set Existencia = (select field FROM Info_Existencias WHERE id=@otherid where sku ='" + x.SKU + "'" +
"AND Tienda =" + tienda, destination);
cmd2.ExecuteNonQuery();
因此,省去foreach语句,仅向数据库启动ONE update语句即可,该语句将通过使用subselect从行中获取正确的值来更新每一行的字段。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.