单条语句插入、更新

Insert, update in single statement

我有两个 table table1 用于添加详细信息, table2 用于添加详细信息table 1.My class 的更新 ID 如下所示:

public bool SetData(List<Serialized> lstSerialized)
{
    string query = "IF NOT EXISTS(SELECT Fid from table1 where Fid=@Fid)" +
                "INSERT INTO table1(" +
                "id, " +
                "Name, " +
                "Fid ,"+                     
                "Detail) OUTPUT INSERTED.id VALUES (" +
                "@id, " +
                "@Name, " +
                "@Fid )"+
               "@Detail)"+
                "ELSE UPDATE table1 SET Name= @Name,Detail= @Detail WHERE Fid = @Fid ";

    return Data.CreateSerialized(lstSerialized, query);
}

public bool CreateSerialized(List<Serialized> lstSerialized, string query)
{
    try
    {
        int Id=0;

        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                int id = GetMaxid();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = id
                cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = lstSerialized[0].Name;
                cmd.Parameters.Add("@Detail", SqlDbType.NVarChar).Value = lstSerialized[0].Detail;
                cmd.Parameters.Add("@Fid ", SqlDbType.Int).Value = lstSerialized[0].Fid;

                con.Open();

                Id= (int)cmd.ExecuteScalar();

                con.Close();
            }

            if (Id!=0)
            {
                using (SqlCommand command = new SqlCommand("update [table2] " +
                                                    "set Index=" + Id + " where " +
                                                    "[IndexID] = " + 9, con))
                {
                    con.Open();
                    int rowsAffected = command.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }
    catch (Exception ex)
    {
        return false;
    }
    return true;
}

插入成功,但更新无法运行,显示错误"Object reference not set to an instance of an object"。我该如何解决这个问题?

在您的更新查询中没有任何 select 语句。当

Id= (int)cmd.ExecuteScalar();

您尝试从此代码转换 ID 但无法转换您的 ID。请处理此部分,您将获得结果。

您可以像这样尝试将对象转换为 int:

 object objId = cmd.ExecuteScalar();
 if (objId != null)
 {
  Id= (int)objId;
 }