Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Before inserting the record check record exists then insert and in else case update the record in database.


for that how can i do in asp.net using c#.
Posted
Comments
frostcox 21-Mar-14 22:35pm    
Can you be more specific? What type of database?
What have you tried and where is the issue?

1. If you are not familiar with C# and sql, then you should go through Using Parameterized SQL[^] first.
2. Once you have completed Point 1, adapt the following code snippet to check if certain record exists in the database.
SQL
string selectSQL = "select count(*) from tablename where somefieldname = @somevalue";
SqlCommand cmd = new SqlCommand(selectSQL);
cmd.Parameters.AddWithValue("@somevalue", TextBox1.Text.Trim());
Int32 rowCount = (Int32) cmd.ExecuteScalar();

3. After Point 3,
SQL
if (rowCount == 0){
  // execute sql insert, adapt example in point 1
}
else
{
  // execute sql update, adapt example in point 1
}

End of lesson.
 
Share this answer
 
v2
Comments
frostcox 21-Mar-14 22:52pm    
Good answer... but I would recommend the use of using statements around any classes which implement IDisposable like SqlConnection & SqlCommand....
Peter Leow 21-Mar-14 23:01pm    
Thank you.
If SQL Server, then seek thee the MERGE statement.
 
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