如果id(对于每个sql行)存在,则更新else插入

时间:2016-06-06 13:43:03

标签: c# sql

我有两张桌子。在第一个表中我有列id,名称, 我想检查第二个表是否存在id(来自第一个表),然后更新名称。 如果id不存在,则插入id,name。

我正在使用此代码,但它无效。

System.Data.SqlClient.SqlCommand CheckNone = new System.Data.SqlClient.SqlCommand("IF EXISTS(SELECT id from test) SELECT 1 ELSE SELECT 0", con);
con.Open();
var result = (int)CheckNone.ExecuteScalar();
if (result == 0)
{
    cmd = new SqlCommand(" insert into test(id,name) select id,name from Tamio.dbo.memberform", con);
    cmd.ExecuteNonQuery();
    con.Close();
}
else
{
    SqlCommand cmd = new SqlCommand(" update test set test.name select memberform.name from Tamio.dbo.memberform", con);
    cmd.ExecuteNonQuery();
    con.Close();

我想成功。 enter image description here

2 个答案:

答案 0 :(得分:1)

Uh

$task_start_date

That will return 1 if any id exists

The update does not match up rows in any way
Not even valid syntax

IF EXISTS(SELECT id from test) SELECT 1 ELSE SELECT 0

syntax may be off as from memory but merge will do this

update test set test.name select memberform.name from Tamio.dbo.memberform

答案 1 :(得分:-1)

Why you use 3 query ? Make it one :

cv

But your update code isnt valid. Probably its the cause of your problem :).