1. Microsoft SQL Server Management Studio 中创建 存储过程
1.1 借助模板资源管理器中的Stored Procedure模板进行修改创建
1.2 直接新建查询中sql创建
(无output参数,无return值)
use database GO create procedure proc_insert @barcode nvarchar(20), @docStatus smallint, --@docType nvarchar(5) = 'SF' --默认值 AS begin insert into tableexample(barcode,doc_status,editdate) values(@barcode,@docStatus,GETDATE()) end
2. c#程序中调用存储过程
2.1 以文本形式调用(CommandType.Text)
SqlConnect conn= new SqlConnect("......"); conn.open(); string tempInsertStr = "EXEC proc_insert @barcode = " + barcode + ", @docStatus = " + (int)docStatus; using (SqlCommand cmd = new SqlCommand(tempInsertStr, Conn)) { cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 10; int result = cmd.ExecuteNonQuery(); }
conn.close();
2.2 以存储过程形式调用(CommandType.StoredProcedure)
SqlConnect conn= new SqlConnect("......"); conn.open(); string tempInsertStr = "proc_insert"; using (SqlCommand cmd = new SqlCommand(tempInsertStr, Conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 10; //添加参数(尽量使用参数形式) cmd.Parameters.Add("@barcode",SqlDbType.VarChar).Value = barcode;
//cmd.Parameters[0].Value= barcode; cmd.Parameters.Add("@docStatus", SqlDbType.SmallInt).Value = (int)docStatus;
//cmd.Parameters[1].Value= docStatus; int result = cmd.ExecuteNonQuery(); } conn.close();