如果表中已存在数据(Ado.net) [英] If Data already Exists in a Table(Ado.net)

查看:190
本文介绍了如果表中已存在数据(Ado.net)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是使用Ado.net存储过程在表格中插入行的代码。



Here is the code for inserting rows in a table using Ado.net stored procedure.

<pre lang="c#">

 IDbConnection conn = null;
            try
            {
                conn = this.GetConnection();
                conn.Open();


                IDbCommand cmd = conn.CreateCommand();
                //string insertSQL = @"insert into Routes(FromCityId,ToCityId,DistanceInKms,Status) values(@fromcityID,@toCityID,@dis,@st);";
                //cmd.CommandText = insertSQL;
                //cmd.CommandType = CommandType.Text;
                cmd.CommandText = "StoredProcedureName";
                cmd.CommandType = CommandType.StoredProcedure;
                IDataParameter p1 = cmd.CreateParameter();
                p1.ParameterName = "@FromCity";
                p1.Value = RouteInfo.FromCity.CityId;
                cmd.Parameters.Add(p1);
                //........................
                return cmd.ExecuteNonQuery();
            }

              
                

            }
            catch (Common.ConnectToDatabaseException)
            {
                throw new RouteDAOException("Unable to add route");
            }
            catch (Exception)
            {
                throw new RouteDAOException("Unable to add route");
            }
            finally
            {
                conn.Close();
            }







我需要提示写一个代码来检查行是否是已存在,如果是,我将不得不创建一个例外。



最好的问候,




I need a hint to write a code for checking if the row is already exists , if yes , I will have to create an exception.

best regards,

推荐答案

在存储过程中使用以下IF语法



use following IF syntax in the stored procedure

IF NOT EXISTS(SELECT * FROM TABLE NAME WHERE <duplicate condition="">)
BEING
  --INSERT INTO TABLENAME (columnName1,..) VALUES (...)
END
</duplicate>


您需要在Sql中检查它。



在SQL中你做



You will want to check for it in Sql.

In SQL you do

IF EXISTS(SELECT * FROM table WHERE field = value)
  BEGIN
    -- do an update since it exists
    UPDATE table 
    SET field1 = value. field2 = value2
    WHERE field = value
  END
ELSE
  BEGIN
    -- Since it does not exist, do an insert
    INSERT INTO ...
  END


这篇关于如果表中已存在数据(Ado.net)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆