检查是否存在每一行分开并运行相同的代码

时间:2016-09-23 14:01:00

标签: c# sql-server sql-server-2008

我有两个表,我想检查条码是否从第一个表到第二个。但我想只为第一行运行代码。当它结束然后为第二行运行相同的代码并对其余的行进行相同的操作直到它结束。

以下是我想要使用的代码示例:但是我将如何分别运行每一行的代码。先用第二个,第三个开始,然后再继续。

代码:For SQL

IF EXISTS ( SELECT Barcode FROM Table_1 where barcode = (select barcode from Table_2)
BEGIN
update Table_2 set Name = (select Name from Table_1)
END

ELSE
BEGIN
insert into Table_2 (Barcode,Name) (select Barcode,name from Table1)
END

enter image description here

代码:对于C#

System.Data.SqlClient.SqlCommand CheckNone = new System.Data.SqlClient.SqlCommand("IF EXISTS( SELECT Barcode FROM Table_1 where barcode = (select barcode from Table_2) SELECT 1 ELSE SELECT 0", con);
con.Open();

var result = (int)CheckNone.ExecuteScalar();
if (result == 0)
{

SqlCommand cmd = new SqlCommand("insert into Table_2 (Barcode,Name) (select Barcode,name from Table1)",con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("update Table_2 set Name = (select Name from Table_1)",con);
cmd.ExecuteNonQuery();
        con.Close();
}
}

1 个答案:

答案 0 :(得分:0)

听起来你需要更新表2中Name表示表1中具有匹配Barcode值的行。您可以在teo查询中为整个表格进行更新:

UPDATE t2
SET Name = t1.Name
FROM Table2 t2
INNER JOIN Table1 t1
  ON t2.Barcode = t1.Barcode

INSERT INTO Table2
(Barcode, Name)
SELECT Barcode, Name
FROM Table1
WHERE Barcode NOT IN
(SELECT Barcode FROM Table2) 

如果确实希望一次更新一行,那么只需将WHERE Barcode = @barcode添加到SELECT查询中,并将参数值传递给C#中的Command。但请注意,它会比一次完成所有操作慢得多。

相关问题