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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Sep 7, 2011, 12:24 PM
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
Prabhu RajaPosted Sep 7, 2011, 5:57 AM
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"