1

我创建了 DataAccessLayer.cs 文件,它帮助我与数据库建立连接以将记录插入数据库,并且我创建了存储过程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class DataAccessLayer
{
    SqlConnection con = new SqlConnection("Connection String");
    SqlCommand cmd;
public DataAccessLayer()
{
    //
    // TODO: Add constructor logic here
    //
}

public int ExecuteProcedure(String procname, SqlParameter[]param)
{
    cmd = new SqlCommand();
    cmd.CommandText = procname;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection = con;

    foreach (SqlParameter obj in param)
    {
        cmd.Parameters.Add(obj);
    }
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();
        return i;
}
}

使用存储过程将记录插入数据库的代码

SqlParameter[] param = new SqlParameter[]
    {
        new SqlParameter("@Name",txtFirstName.Text),
        new SqlParameter("@DOB",txtDOB.Text),
        new SqlParameter("@Address",txtAddress.Text),
        new SqlParameter("@CN",ddlCountry.SelectedValue),
        new SqlParameter("@SN",ddlState.SelectedValue),
        new SqlParameter("CNN",ddlCity.SelectedValue),
        new SqlParameter("@Mobile",txtMobile.Text),
        new SqlParameter("@Email",txtEmail.Text),
        new SqlParameter("@Pincode",txtPincode.Text),
        new SqlParameter("@returnval",SqlDbType.Int)
    };
    int i = DAL.ExecuteProcedure("AddContactInfo", param);
    if (i == 1)
    {
        lblError.Text = "Sucess";
    }
    else 
    {
        lblError.Text = "Not Sucess";
    }

用于插入记录的存储过程

ALTER proc [dbo].[AddContactInfo]
(
@Name varchar(50),
@DOB datetime,
@Address Varchar(max),
@Mobile varchar(15),
@Email varchar(50),
@CN int,
@SN int,
@CNN int,
@Pincode int,
@returnval int output
)
As
Begin
if exists(select Id from Contact_Info where Email=@Email)
begin
set @returnval=-2;
return @returnval;
end
else
begin
insert into          Contact_Info(Name,DOB,Address,CountryName,StateName,CityName,Pincode,Mobile,Email,CreatedOn    )
values(@Name,@DOB,@Address,@CN,@SN,@CNN,@Pincode,@Mobile,@Email,GETDATE())

if @@ERROR<>0
begin
    set @returnval=-3;
    return @returnval;
end
else
begin
    set @returnval=1;
    return @returnval;
end
end
End
4

1 回答 1

2

但我收到错误消息,即“过程或函数‘AddContactInfo’需要参数‘@returnval’,但未提供。”

您必须将您设置new SqlParameter("@returnval", SqlDbType.Int)output参数:

foreach (SqlParameter obj in param)
{
    if (cmd.ParameterName == "@returnval")
    {
        cmd.Direction = ParameterDirection.Output
    }

    cmd.Parameters.Add(obj);
}

当然,这期望所有 SP@returnval在适当的时候都具有相同的值。最好在创建参数列表时设置它。

于 2013-10-27T09:56:18.337 回答