/// <summary>
/// 执行Sql语句SqlStr返回bool(是否存在满足条件的记录)
/// protected static bool ExeSqlExist(string SqlStr)
/// </summary>
/// <param name="SqlStr"></param>
/// <returns></returns>
#region 执行Sql语句SqlStr返回bool(是否存在满足条件的记录)
protected static bool ExeSqlExist(string SqlStr)
{
SqlConnection myCon=new SqlConnection(conStr);
SqlCommand myCom=new SqlCommand(SqlStr,myCon);
try
{
myCon.Open();
SqlDataReader myReader=myCom.ExecuteReader();
if (myReader.Read())
return true;
else
return false; }
catch(System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
myCom.Dispose();
myCon.Close();
}
}
#endregion

解决方案 »

  1.   

    判断一条记录是否存在:select count(*) from table where id=1如果不为0则存在,否则不存在。但如果是在SQL中,可以使用EXIST来判断,这样效率高些,因为只要检测有一条就可以了,而上面的语句会搜索整个表的。如果是在C#中,要处理有点麻烦,不过,如果使用SQLCOMMANDBUILDER就简单了:SqlDataAdapter sqlDA=new ..SqlCommandBuilder scb=new SqlCommandBuilder(sqlDA);sqlDA.InsertCommand=scb.GetInsertCommand();
    sqlDA.UpdateCommand=scb.GetUpdateCommand();
    sqlDA.DeleteCommand=scb.GetDeleteCommand();这样,当你把sqlDA的数据放到一个TABLE后,然后通过代码在TABLE中进行数据的修改(删除、添加、更新等),只要调用:
    sqlDA.Update(..)
    就可以轻松完成。
      

  2.   

    Sql语句:
    If Exists (Select *** From *** Where ID = ***)
        Update *** Set *** = *** Where ID = ***
    Else
        Insert.....