create proc Articles_InsertArticle
@AddDate datetime,
@AddBy nvarchar(50),
@CategoryId int,
@Title nvarchar(50),
@Abstract nvarchar(50),
@Body ntext,
@Country nvarchar(50),
@State nvarchar(50),
@City nvarchar(50),
@ReleaseDate datetime,
@ExpireDate datetime,
@Approved bit,
@Listed bit,
@CommentsEnabled bit,
@OnlyFormembers bit,
@ArticleId int output
as
set nocount on
insert into Articles
(AddDate,AddBy,CategoryId,Title,Abstract,Body,Country,State,City,
ReleaseDate,ExpireDate,Approved,Listed,CommentsEnabled,OnlyFormembers
)
values
(@AddDate,@AddBy,@CategoryId,@Title,@Abstract,@Body,@Country,@State,@City,
@ReleaseDate,@ExpireDate,@Approved,@Listed,@CommentsEnabled,@OnlyFormembers
)
SqlConnection conn = new SqlConnection("server=localhost;database=dbDemo;uid=sa");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure; //指定执行存储过程操作
cmd.CommandText = "QueryInfoByName"; //存储过程名称
//对应存储过程QueryInfoByName的第一个参数@name
SqlParameter parName = new SqlParameter("@name", SqlDbType.VarChar, 50);
//指定参数@name要转入的值
parName.Value = txt_name;
//对应存储过程QueryInfoByName的第二个参数@age
SqlParameter parAge = new SqlParameter("@age", SqlDbType.Int);
//指定参数@age要转入的值
parAge.Value = txt_age;
//这一步非常重要,一定将设置好的两个参数类型添加到Command对象的参数集合里
cmd.Parameters.Add(parName);
cmd.Parameters.Add(parAge);
//方式一,查询回来的结果需要显示在DataGrid之类的控件上
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
//方式二,按单个值读取
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Response.Write(reader.GetString(0));
}
}
conn.Close();
}
先指出一下...你的output参数没有赋值,怎么能输出啊?应该在存储过程最后加一句改为:
set @ArticleId=@@IDENTITY 。这样这个存储过程才能有输出参数。下面看调用:
假设你sqlHelper 的连接啥都有了,这里不罗嗦了。
string sql ="Articles_InsertArticle";
SqlParameter[] sp = new SqlParameter[16];
sp[0] = new SqlParameter("@AddDate", SqlDbType.DateTime);
sp[0].Value = DateTime.Now;
sp[1] = new SqlParameter("@AddBy ", SqlDbType.NVarChar);
sp[1].Value = "参数传入值啥的";
......
sp[15] = new SqlParameter("@ArticleId", SqlDbType.Int);
sp[15].Direction = ParameterDirection.Output;//默认不设都是输入参数,输出参数或者返回值必须设下
SqlHelper.ExecuteNonQuery(CommandType.StoredProcedure, sql, sp);//这个方法是把SqlParameter数组都 add 到cmd.Parameters里,不知你的sqlHelp有没这个方法。有就直接用,没有自己写个。
int ID=int.Parse(sp[15].Value.ToString());//取出输出值