Click here to Skip to main content
15,888,073 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Here is the code for inserting rows in a table using Ado.net stored procedure.

C#
<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,
Posted
Comments
Maciej Los 3-Mar-14 15:20pm    
Based on what condition?
Sergey Alexandrovich Kryukov 3-Mar-14 15:22pm    
What is going to happen is you add the duplicate record? How about just having a unique key?
—SA

use following IF syntax in the stored procedure

SQL
IF NOT EXISTS(SELECT * FROM TABLE NAME WHERE <duplicate condition="">)
BEING
  --INSERT INTO TABLENAME (columnName1,..) VALUES (...)
END
</duplicate>
 
Share this answer
 
You will want to check for it in Sql.

In SQL you do

SQL
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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900