存储过程学习笔记(二) 返回值
我们在写一些存储过程的时候总想获取到一些值,比方说,刚刚插入一条记录的ID,等等
(一)通过output获取返回值
存储过程如下
ALTER procedure [dbo].[teturn_test2]
@rg1 int output
as
set @rg1=123
@rg1 int output
as
set @rg1=123
说明:@rg1 为输出值
C#代码中接受
string connectStr = @"server=localhost\sql2005;database=store_procedure;uid=sa; pwd=;";
SqlConnection sqlConnection = new SqlConnection(connectStr);
SqlCommand sqlCommand = new SqlCommand("teturn_test2", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@rg1", SqlDbType.Int));
sqlCommand.Parameters[0].Direction = ParameterDirection.Output; //这一句表明这一参数为输出类型的
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
int rg1= (int)sqlCommand.Parameters[0].Value;
sqlConnection.Close();
SqlConnection sqlConnection = new SqlConnection(connectStr);
SqlCommand sqlCommand = new SqlCommand("teturn_test2", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@rg1", SqlDbType.Int));
sqlCommand.Parameters[0].Direction = ParameterDirection.Output; //这一句表明这一参数为输出类型的
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
int rg1= (int)sqlCommand.Parameters[0].Value;
sqlConnection.Close();
(二)通过return获取返回值
存储过程如下
ALTER procedure [dbo].[return_test3]
@pid int
as
begin
if(@pid=0)
begin
return 100
end
else
begin
return 200
end
end
@pid int
as
begin
if(@pid=0)
begin
return 100
end
else
begin
return 200
end
end
代码中获取如下
string connectStr = @"server=localhost\sql2005;database=store_procedure;uid=sa;pwd=;";
SqlConnection sqlConnection = new SqlConnection(connectStr);
SqlCommand sqlCommand = new SqlCommand("return_test3", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@result", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@pid", SqlDbType.Int));
sqlCommand.Parameters[0].Direction = ParameterDirection.ReturnValue;
sqlCommand.Parameters[1].Value = 1;
sqlConnection.Open();
int r = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
int rg1 = (int)sqlCommand.Parameters[0].Value;
SqlConnection sqlConnection = new SqlConnection(connectStr);
SqlCommand sqlCommand = new SqlCommand("return_test3", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("@result", SqlDbType.Int));
sqlCommand.Parameters.Add(new SqlParameter("@pid", SqlDbType.Int));
sqlCommand.Parameters[0].Direction = ParameterDirection.ReturnValue;
sqlCommand.Parameters[1].Value = 1;
sqlConnection.Open();
int r = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
int rg1 = (int)sqlCommand.Parameters[0].Value;
执行程序输出的根据@pid的值不同,返回不同的@result的值