1.--SqlServer创建存储过程
create proc [dbo].[P_insert_gads]
--定义参数
@type int,
@uid int,
@uname nvarchar(50),
@address nvarchar(50),
@remark ntext,
@pass nvarchar(50),
@uphone nvarchar(12),
--定义输出参数
@result nvarchar(20) output
as
--if--else嵌套
if(@type=1)
begin
if(@uid<10)
begin
insert into student([uid],[uname],[address],remark)
values(@uid,@uname,@address,'秀儿')
--参数赋值
set @result='student表添加成功'
end
else if(@uid>=10 and @uid<20)
begin
insert into student([uid],[uname],[address],remark)
values(@uid,@uname,@address,'潜力股')
set @result='student表添加成功'
end
else
begin
insert into student([uid],[uname],[address],remark)
values(@uid,@uname,@address,'不合格')
set @result='student表添加成功'
end
end
else
begin
if
exists(select top 1 * from adminInfo where uid=@uid)
set @result='adminInfo已存在'
else
begin
insert into adminInfo([uid],[uName],[uPassword],[uPhone])
values(@uid,@uname,@pass,@uphone)
set @result='adminInfo表添加成功'
end
end
--输出
print @result
GO
2.c#程序中调用存储过程
private static string Proc_Setting(string [] info) {
string result = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conStr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
//通过con连接数据库用cmd执行这个P_insert_gads存储过程
SqlCommand cmd = new SqlCommand("[P_insert_gads]", con);
//标记执行的是存储过程
cmd.CommandType = CommandType.StoredProcedure;
//创建存储过程所需参数
SqlParameter[] parment = {
new SqlParameter("@type",SqlDbType.NVarChar),
new SqlParameter("@uid",SqlDbType.NVarChar),
new SqlParameter("@uName",SqlDbType.NVarChar,50),
new SqlParameter("@pass",SqlDbType.NVarChar,50),
new SqlParameter("@address",SqlDbType.NVarChar,50),
new SqlParameter("@uphone",SqlDbType.NVarChar,12),
new SqlParameter("@remark",SqlDbType.NText),
new SqlParameter("@result",SqlDbType.NVarChar,20){
//给参数设置输出标记
Direction=ParameterDirection.Output
}
};
int i = 0;
//参数赋值
foreach (var item in parment)
{
item.Value = info[i];
i++;
}
cmd.Parameters.AddRange(parment);
//执行存储过程
cmd.ExecuteNonQuery();
//获取输出结果
result = cmd.Parameters["@result"].Value.ToString();
con.Close();
}
return result;
}