简单的插入数据存储过程SCOPE_IDENTITY()(一)

2014-11-24 17:01:17 · 作者: · 浏览: 8
简单的插入数据存储过程SCOPE_IDENTITY()
< asp:Button ID="btnPublish" runat="server" Text="发送" OnClick="btnPublish_Click" />
protected void btnPublish_Click(object sender, EventArgs e)
{
int temp = -1;
int mCustomerID =0;
if (ViewState["CID"] != null)
{
mCustomerID = Convert.ToInt32(ViewState["CID"].ToString());
}
string company = this.mCompany.Text;
string name = this.mName.Text.Trim();
string mail = this.mMail.Text.Trim();
string tel = this.mTel.Text.Trim();
string content = this.mContent.InnerText;
SqlConnection con = null;
try
{
con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "AddGuestBooks";
con.Open();
SqlParameter[] sp =
{
new SqlParameter("@Creater",SqlDbType.NVarChar,100)
,new SqlParameter("@CompanyName",SqlDbType.NVarChar,100)
,new SqlParameter("@Contact",SqlDbType.NVarChar,20)
,new SqlParameter("@Email",SqlDbType.VarChar,50)
,new SqlParameter("@Tel",SqlDbType.VarChar,50)
,new SqlParameter("@Content",SqlDbType.NVarChar,300)
,new SqlParameter("@ReturnValue",SqlDbType.Int)
};
sp[0].Value = mCustomerID;
sp[1].Value = company;
sp[2].Value = name;
sp[3].Value = mail;
sp[4].Value = tel;
sp[5].Value = content;
sp[6].Direction = ParameterDirection.Output;
com.Parameters.AddRange(sp);
com.ExecuteNonQuery();
temp = Convert.ToInt32(com.Parameters["@ReturnValue"].Value);
con.Close();
}
catch (SqlException se)
{
}
finally
{
con.Close();
}
if (temp == -1)
{
myShare.WebMessageBox(this.Page, "留言发送时出错,请重试!");
}
else if (temp == 0)
{
myShare.WebMessageBox(this.Page, "留言发送失败,请重试!");
}
else
{
Page p = (Page)System.Web.HttpContext.Current.Handler;
p.ClientScript.RegisterStartupScript(p.GetType(), "提示", "<script>alert('信息发送成功!');window.location='BuyInfoList.aspx'");
this.mCompany.Text = "";
this.mName.Text = "";
this.mMail.Text = "";
this.mTel.Text = "";
}
}
Create proc AddGuestBooks
@Creater int,
@CompanyName NVarChar(100),
@Contact NVarChar(20),
@Email VarChar(50),
@Tel VarChar(20),
@Content NVarChar(300),
@ReturnValue Int output
WITH ENCRYPTION AS
begin
set @ReturnValue=0
DECLARE @EC_TempID int
BEGIN
insert into GuestBooks(Creater,CompanyName,Contact,Email,Tel,Content)
values(@Creater,@CompanyName,@Contact,@Email,@Tel,@Content)
SELECT @EC_TempID=SCOPE_IDENTITY()
IF @EC_TempID=0
BEGIN
SET @ReturnValue=-1
END
else
begin
set @ReturnValue=@EC_TempID