Win2003+Vs2003+Oracle9.0
建立Oracle的預存程序,如果有參數,不論是in或者out類型的,都不能夠指定參數的大小,理由很簡單,無法判斷。
建立過程: Create or replace procedure procedure_test(inpara1 in varchar2,
inpara2 in varchar2
)
as
begin
..
end procedure_test;
/
我們無法預知procedure_test的調用者傳參數時,inpara1,inpara2的長度會是多少。
如果使用Ado.Net ,用OleDbCommand調用這個過程,那麼必須指定對應inpara1,inpara2的OleDbParameter的長度。
即使參數類型是out 的,也必須指定長度,曾經看O'Reilly的Ado.Net in a Nullshell一書,在講調用out型別參數的過程時,所舉的例子的參數為Int 型,沒有再顯示指定參數長度Size,當時誤以為對於out類型的無須指定,但是在實際應用中,對於字元型參數,如果沒有長度,會報0Size的錯誤,必須顯示指定Size,才可以調用過程;而對於Int類型的,都有自己的預設長度吧。
附調用參數為out類型的函數: /**//// <summary>
/// 調用預存程序,參數都是out型的,
/// 返回參數的長度不定義
/// </summary>
/// <param name="procedureName">過程名</param>
/// <param name="para">參數,接收傳回值</param>
[LastModified("2006-01-05","調用預存程序,過程的參數都是out類型的")]
[LastModified("2006-01-17","設定參數的Size")]
public virtual void CallProcedureOut(string procedureName,ref string[] para)
{
try
{
ConnectionPrepare(true);
OleDbCommand Cmd=OraCon.CreateCommand();
Cmd.CommandType=CommandType.StoredProcedure;
Cmd.CommandText=procedureName;
//假設接收的參數的長度最大為800
for(int i=0;i<para.Length;i++)
{
OleDbParameter Parameter=new OleDbParameter(@"para"+i,OleDbType.VarChar,800);
Parameter.Direction=ParameterDirection.Output;
Cmd.Parameters.Add(Parameter);
}
//調用預存程序
Cmd.ExecuteNonQuery();
//擷取調用預存程序後參數的值
for(int i=0;i<para.Length;i++)
{
para[i]=Cmd.Parameters[i].Value.ToString().Trim().Replace("\0","");
}
}
catch(OleDbException oraex)
{
throw oraex;
}
catch(Exception ex)
{
throw ex;
}
finally
{
ConnectionPrepare(false);
}
}
附O'Reilly的例子:
過程: CREATE Procedure CustomerAdd
(
@FullName nvarchar(50),
@Email nvarchar(50),
@Password nvarchar(50),
@CustomerID int OUTPUT
)
AS
INSERT INTO Customers
(
FullName,
EMailAddress,
Password
)
VALUES
(
@FullName,
@Email,
@Password
)
SELECT
@CustomerID = @@Identity
GO
Ado.Net 調用: using System;
using System.Data;
using System.Data.SqlClient;
public class AddCustomer
{
public static void Main()
{
string connectionString = "Data Source=localhost;" +
"Initial Catalog=store;Integrated Security=SSPI";
string procedure = "CustomerAdd";
// Create ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(procedure, con);
// Configure command and add input parameters.
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param;
param = cmd.Parameters.Add("@FullName", SqlDbType.NVarChar, 50);
param.Value = "John Smith";
param = cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50);
param.Value = "john@mydomain.com";
param = cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50);
param.Value = "opensesame";
// Add the output parameter.
param = cmd.Parameters.Add("@CustomerID", SqlDbType.Int);
param.Direction = ParameterDirection.Output;
// Execute the command.
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Console.WriteLine("New customer has ID of " + param.Value);
}
}