本文包括用SqlClient和Odbc兩種連接方式調用SqlServer的存儲過程,這兩種方式有細微的區別:
存儲過程名爲‘MaxAge’,包括輸入參數和輸出參數,輸出只能人員的最大年齡。數據庫爲自建的test數據庫,包括一個名爲useName的表,字段有id(itn);name(nvarchar(10));age(int)
存儲過程如下:
if Exists(select name from sysobjects where type='p' and name='MaxAge')
drop proc MaxAge
go
create proc MaxAge
(@Name1 nvarchar(10),
@Name2 nVarchar(10),
@MaxAge int output)
as
select @MaxAge=Max(age) from dbo.UserName where name=@Name1 or name=@Name2
使用SqlClient調用存儲過程的方法如下:
SqlConnection con = new SqlConnection("server=PC-200201070359;uid=sa;pwd=123;database=test;");
try
{
con.Open();
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MaxAge"; //存儲過程名稱
//輸入參數
SqlParameter para = new SqlParameter("@Name1", "James");
command.Parameters.Add(para);
//輸入參數
para = new SqlParameter("@Name2", "Mary");
command.Parameters.Add(para);
//輸出參數(參數名稱大小寫無關)
para = new SqlParameter("@Maxage", SqlDbType.Int, 4);
para.Direction = ParameterDirection.Output;
command.Parameters.Add(para);
int i = command.ExecuteNonQuery(); //執行成功返回-1
string k = command.Parameters["@Maxage"].Value.ToString();
}
catch (Exception ex)
{
//throw;
}
使用Odbc調用存儲過程的方法如下:
OdbcConnection con = new OdbcConnection("Driver={SQL Server};server=PC-200201070359;uid=sa;pwd=123;database=test;");
try
{
con.Open();
OdbcCommand command = new OdbcCommand();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
//command.CommandText = "MaxAge"; //存儲過程名稱
command.CommandText = "{call MaxAge (?, ?,?)}";
//輸入參數
OdbcParameter para = new OdbcParameter("@Name1", OdbcType.NVarChar, 10);
para.Value = "James";
command.Parameters.Add(para);
//輸入參數
para = new OdbcParameter("@Name2", OdbcType.NVarChar, 10);
para.Value = "Mary";
command.Parameters.Add(para);
//輸出參數(參數名稱大小寫無關)
para = new OdbcParameter("@MaxAge", OdbcType.Int, 4);
para.Direction = ParameterDirection.Output;
command.Parameters.Add(para);
int i = command.ExecuteNonQuery(); //執行成功返回-1
string k = command.Parameters["@Maxage"].Value.ToString();
}
catch (Exception ex)
{
//throw;
}
可能遇到的問題:
使用ODBC方法,只能方法時會報這樣的異常:ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]過程 'MaxAge' 需要參數 '@Name1',但未提供該參數。
解決辦法:將command.CommandText = "MaxAge"; //存儲過程名稱 改爲 command.CommandText = "{call MaxAge (?, ?,?)}";即可,目前原因未知;前面的方法在sqlclient中是可用的
原文: http://www.cnblogs.com/gossip/archive/2009/06/15/1503884.html