hi everyone,
Help me to code my csharp project, i just want to upsert code....if exist update and if not exist insert to my sql server database table.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Prabhu RajaRank #861 · 2.6K reputationPosted Sep 7, 2011, 1:57 AM EDT
IF EXISTS (SELECT * FROM tablename WHERE columnname = @Id)
BEGIN
--UPDATE HERE
END
ELSE
BEGIN
-- INSERT HERE
END
---------------------------------------------
If it helps you, mark it as "Correct Answer"
Satyapriya NayakRank #47 · 31.5K reputationPosted Sep 7, 2011, 8:24 AM EDT
Here is you desired code.Run the attachments.
Create a table employee as below
Create table employee(eid varchar(50)primary key,ename varchar(50))
Create a stored procedure display as below
ALTER PROCEDURE dbo.display
@eid varchar(50),
@ename varchar(50)
AS
IF EXISTS (SELECT * FROM employee WHERE eid = @eid)
BEGIN
update employee set ename=@ename where eid=@eid
END
ELSE
BEGIN
insert employee(eid,ename) values (@eid,@ename)
END
Default.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Default.aspx.cs code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
protected void btn1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
com = new SqlCommand("display", con);
com.Parameters.Add("@eid", SqlDbType.VarChar).Value = txtUserId.Text;
com.Parameters.Add("@ename", SqlDbType.VarChar).Value = txtUserName.Text;
com.CommandType = CommandType.StoredProcedure;
com.ExecuteNonQuery();
con.Close();
bindgrid();
}
protected void Page_Load(object sender, EventArgs e)
{
bindgrid();
}
void bindgrid()
{
SqlConnection con = new SqlConnection(strConnString);
str = "select * from employee";
com = new SqlCommand(str, con);
ds = new DataSet();
com.Connection = con;
com.CommandText = "SELECT * FROM employee";
sqlda = new SqlDataAdapter(com);
sqlda.Fill(ds, "employee");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
Thanks
If this post helps you mark it as answer