Linq to SQL bulkupdate来自2个不同的数据库,2个不同的表

时间:2017-06-13 20:33:51

标签: c# sql sql-server linq-to-sql

您好我正在使用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更新它的参数。

感谢您的时间

1 个答案:

答案 0 :(得分:0)

由于它位于两个不同的表中,因此在不知道表格设计的情况下难以选择第二个表格中的相应行。但你可以这样做:

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语句,该语句将使用子选择更新每一行的字段,以从行中获取正确的值。

希望这有帮助。

相关问题