废话不多说,直接给大家贴C#代码了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/// <summary> /// 执行存储过程,返回" 返回值" /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>执行存储过程的返回值</returns> public static int RunProcedureWithReturn( string storedProcName, IDataParameter[] parameters) { using (SqlConnection connection = new SqlConnection(connectionString)) { int result; connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); command.ExecuteNonQuery(); result = ( int )command.Parameters[ "ReturnValue" ].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 SqlCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlCommand 对象实例</returns> private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add( new SqlParameter( "ReturnValue" , SqlDbType.Int, 4, ParameterDirection.ReturnValue, false , 0, 0, string .Empty, DataRowVersion.Default, null )); return command; } |
ps:在C#中调用存储过程中的两种返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//存储过程 //create proc authors_count @outrus int output //as //declare @authors int //select @authors=count(*) from authors //set @outrus=@authors //return @authors System.Data.SqlClient.SqlConnection sqlcon= new System.Data.SqlClient.SqlConnection( "server=(local);database=pubs;uid=sa;pwd=;" ); System.Data.SqlClient.SqlCommand sqlcmd= new System.Data.SqlClient.SqlCommand( "authors_count" ,sqlcon); sqlcmd.CommandType=System.Data.CommandType.StoredProcedure; // sqlcmd.CommandText="authors_count"; // sqlcmd.Connection=sqlcon; sqlcmd.Parameters.Add( "@rus" ,System.Data.SqlDbType.Int); sqlcmd.Parameters.Add( "@outrus" ,System.Data.SqlDbType.Int); sqlcmd.Parameters[0].Direction=System.Data.ParameterDirection.ReturnValue; sqlcmd.Parameters[1].Direction=System.Data.ParameterDirection.Output; sqlcon.Open(); //int res=(int)sqlcmd.ExecuteNonQuery();//此时返回的不是存储过程的返回值,以上只是返回delete,update,insert所影响的行数 sqlcmd.ExecuteNonQuery(); string res=sqlcmd.Parameters[0].Value.ToString(); //这样就可以得到存储过程的返回值 sqlcon.Close(); this .label1.Text= "存储过程的返回值是:" +res.ToString(); //由return 返回 this .label2.Text= "存储过程中返回的output值:" +sqlcmd.Parameters[1].Value.ToString(); //由output返回 |