原文地址:http://www.2cto.com/kf/201110/109214.html
CREATE TABLE Table_1
(
tid int identity(1,1),
number int
)
1.调用无参数无返回值的存储过程
CREATE PROC proc_1
AS
INSERT Table_1 (number) VALUES (100);
GO
调用方法:
SqlCommand cmd = new SqlCommand("proc_1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
2.调用有参数有返回
CREATE PROC proc_2
@result int OUTPUT,
@number int,
@tid int
AS
UPDATE Table_1 SET number = number + @number WHERE tid = @tid;
SELECT @result = number FROM Table_1;
GO
调用方法:
public static int exec_proc_2(int number, int tid)
{
SqlCommand cmd = new SqlCommand("proc_2", conn);
cmd.CommandType = CommandType.StoredProcedure;
// 添加一个名为@result的参数,数据类型为SqlDbType.Int
cmd.Parameters.Add(new SqlParameter("@result", SqlDbType.Int));
// 将@result参数设置为接收输出参数
cmd.Parameters["@result"].Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@number", number);
cmd.Parameters.AddWithValue("@tid", tid);
cmd.ExecuteNonQuery();
// 将输出的Object数据转换成int类型
int result = (int)cmd.Parameters["@result"].Value;
return result;
}
3.调用返回一张表的存储过程并接收
CREATE PROC proc_3
AS
SLECT * FROM Table_1;
GO
调用方法:
public static DataTable exec_proc_3()
{
SqlCommand cmd = new SqlCommand("proc_3", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
return table;
}