.NET Framework Developer's Guide Working with Command Parameters Command objects use parameters to pass values to SQL statements or stored procedures, providing type checking and validation. Unlike command text, parameter input is treated as a literal value, not as executable code. This helps guard against "SQL injection" attacks, in which an attacker inserts a command into an SQL statement that compromises security on the server. In addition to the security benefits, parameterized commands provide a convenient method for organizing values passed to a data source. A DbParameter object can be created using its constructor, or by adding it to the DbParameterCollection by calling the Add method of the DbParameterCollection()()() collection. The Add method will take as input either constructor arguments or an existing parameter object, depending on the data provider.
 Supplying the ParameterDirection Property
When adding parameters, you need to supply a ParameterDirection property for parameters other than input parameters. The following table shows the ParameterDirection values you can use with the ParameterDirection enumeration. | Member name | Description | | Input | The parameter is an input parameter. This is the default. | | InputOutput | The parameter is capable of both input and output. | | Output | The parameter is an output parameter. | | ReturnValue | The parameter represents a return value from an operation such as a stored procedure, built-in function, or user-defined function. |
 Working with Parameter Placeholders
The syntax for parameter placeholders depends on the data source. The .NET Framework data providers handle naming and specifying parameters and parameter placeholders differently. This syntax is tailored to a specific data source, as described in the following table. | Data provider | Parameter naming syntax | | SqlClient | Uses named parameters in the format @parametername. | | OleDb | Uses positional parameter markers indicated by a question mark (?). | | Odbc | Uses positional parameter markers indicated by a question mark (?). | | OracleClient | Uses named parameters in the format :parmname (or parmname). |
 Specifying Parameter Data Types
The data type of a parameter is specific to the .NET Framework data provider. Specifying the type converts the value of the Parameter to the .NET Framework data provider type before passing the value to the data source. You may also specify the type of a Parameter in a generic fashion by setting the DbType property of the Parameter object to a particular DbType. The .NET Framework data provider type of a Parameter object is inferred from the .NET Framework type of the Value of the Parameter object, or from the DbType of the Parameter object. The following table shows the inferred Parameter type based on the object passed as the Parameter value or the specified DbType. | .NET Framework type | System.Data.DbType | SqlDbType | OleDbType | OdbcType | OracleType | | bool | Boolean | Bit | Boolean | Bit | Byte | | byte | Byte | TinyInt | UnsignedTinyInt | TinyInt | Byte | | byte[] | Binary | VarBinary. This implicit conversion will fail if the byte array is greater than the maximum size of a VarBinary, which is 8000 bytes.For byte arrays larger than 8000 bytes, explicitly set the SqlDbType. | VarBinary | Binary | Raw | | char | | Inferring a SqlDbType from char is not supported. | Char | Char | Byte | | DateTime | DateTime | DateTime | DBTimeStamp | DateTime | DateTime | | Decimal | Decimal | Decimal | Decimal | Numeric | Number | | double | Double | Float | Double | Double | Double | | float | Single | Real | Single | Real | Float | | Guid | Guid | UniqueIdentifier | Guid | UniqueIdentifier | Raw | | Int16 | Int16 | SmallInt | SmallInt | SmallInt | Int16 | | Int32 | Int32 | Int | Int | Int | Int32 | | Int64 | Int64 | BigInt | BigInt | BigInt | Number | | object | Object | Variant | Variant | Inferring an OdbcType from Object is not supported. | Blob | | string | String | NVarChar . This implicit conversion will fail if the string is greater than the maximum size of an NVarChar, which is 4000 characters. For strings greater than 4000 characters, explicitly set the SqlDbType. | VarWChar | NVarChar | NVarChar | | TimeSpan | Time | Inferring a SqlDbType from TimeSpan is not supported. | DBTime | Time | DateTime | | UInt16 | UInt16 | Inferring a SqlDbType from UInt16 is not supported. | UnsignedSmallInt | Int | UInt16 | | UInt32 | UInt32 | Inferring a SqlDbType from UInt32 is not supported. | UnsignedInt | BigInt | UInt32 | | UInt64 | UInt64 | Inferring a SqlDbType from UInt64 is not supported. | UnsignedBigInt | Numeric | Number | | | AnsiString | VarChar | VarChar | VarChar | VarChar | | | AnsiStringFixedLength | Char | Char | Char | Char | | | Currency | Money | Currency | Inferring an OdbcType from Currency is not supported. | Number | | | Date | Inferring a SqlType from Date is not supported. | DBDate | Date | DateTime | | | SByte | Inferring a SqlType from SByte is not supported. | TinyInt | Inferring an OdbcType from SByte is not supported. | SByte | | | StringFixedLength | NChar | WChar | NChar | NChar | | | Time | Inferring a SqlType from Time is not supported. | DBTime | Time | DateTime | | | VarNumeric | Inferring a SqlDbType from VarNumeric is not supported. | VarNumeric | Inferring an OdbcType from VarNumeric is not supported. | Number | Note: | | Conversions from Decimal to other types are narrowing conversions that round the Decimal value to the nearest integer value toward zero. If the result of the conversion is not representable in the destination type, an OverflowException is thrown. | Note: | | When you send a null parameter value to the server, you must specify DBNull, not null (Nothing in Visual Basic). The null value in the system is an empty object that has no value. DBNull is used to represent null values. For more information on database nulls, see Handling Null Values. |
 Deriving Parameter Information
Parameters can also be derived from a stored procedure using the DbCommandBuilder class. Both the SqlCommandBuilder and OleDbCommandBuilder classes provide a static method, DeriveParameters, which automatically populates the parameters collection of a command object with parameter information from a stored procedure. Note that DeriveParameters overwrites any existing parameter information for the command. Note: | | Deriving parameter information incurs a performance penalty because it requires an additional round trip to the data source to retrieve the information. If parameter information is known at design time, you can improve the performance of your application by setting the parameters explicitly. | For more information, see Automatically Generating Commands.
 Using Parameters with a SqlCommand and a Stored Procedure
Stored procedures offer many advantages in data-driven applications. Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security. Although a stored procedure can be called by simply passing the stored procedure name followed by parameter arguments as an SQL statement, using the Parameters collection of the ADO.NET DbCommand object enables you to more explicitly define stored procedure parameters, as well as to access output parameters and return values. Note: | | Parameterized statements are executed on the server using sp_executesql, which allows for query plan reuse. Local cursors or variables in the sp_executesql batch are not visible to the batch that calls sp_executesql. Changes in database context last only to the end of the sp_executesql statement. For more information, see SQL Server Books Online. | When using parameters with a SqlCommand to execute a SQL Server stored procedure, the names of the parameters added to the Parameters collection must match the names of the parameter markers in the stored procedure. The .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to an SQL statement or a stored procedure. It treats parameters in the stored procedure as named parameters and searches for matching parameter markers. For example, the CustOrderHist stored procedure is defined with a parameter named @CustomerID. When your code executes the stored procedure it must also use a parameter named @CustomerID. CREATE PROCEDURE dbo.CustOrderHist @CustomerID varchar(5) Example This example demonstrates how to call a SQL Server stored procedure in the Northwind sample database. The name of the stored procedure is dbo.SalesByCategory and it has an input parameter named @CategoryName with a data type of nvarchar(15). The code creates a new SqlConnection inside of a using block so that the connection is disposed when the procedure ends. The SqlCommand and SqlParameter objects are created, and their properties set. A SqlDataReader executes the SqlCommand and returns the result set from the stored procedure, displaying the output in the console window. Note: | | Instead of creating SqlCommand and SqlParameter objects and then setting properties in separate statements, you can instead elect to use one of the overloaded constructors to set multiple properties in a single statement. | GetSalesByCategory( connectionString , _
categoryName )
connection SqlConnection(connectionString)
command SqlCommand = SqlCommand()
command.Connection = connection
command.CommandText =
command.CommandType = CommandType.StoredProcedure
parameter SqlParameter()
parameter.ParameterName =
parameter.SqlDbType = SqlDbType.NVarChar
parameter.Direction = ParameterDirection.Input
parameter.Value = categoryName
command.Parameters.Add(parameter)
connection.Open()
reader SqlDataReader = command.ExecuteReader()
reader.HasRows
Do reader.Read()
Console.WriteLine(, _
reader(0), reader(1))
Console.WriteLine()
GetSalesByCategory(string connectionString,
string categoryName)
{
(SqlConnection connection = SqlConnection(connectionString))
{
SqlCommand command = SqlCommand();
command.Connection = connection;
command.CommandText = ;
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = SqlParameter();
parameter.ParameterName = ;
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
command.Parameters.Add(parameter);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
(reader.HasRows)
{
(reader.Read())
{
Console.WriteLine(, reader[0], reader[1]);
}
}
{
Console.WriteLine();
}
reader.Close();
}
}
 Using Parameters with an OleDbCommand or OdbcCommand
When using parameters with an OleDbCommand or OdbcCommand, the order of the parameters added to the Parameters collection must match the order of the parameters defined in your stored procedure. The .NET Framework Data Provider for OLE DB and .NET Framework Data Provider for ODBC treat parameters in a stored procedure as placeholders and apply parameter values in order. In addition, return value parameters must be the first parameters added to the Parameters collection. The .NET Framework Data Provider for OLE DB and .NET Framework Data Provider for ODBC do not support named parameters for passing parameters to an SQL statement or a stored procedure. In this case, you must use the question mark (?) placeholder, as in the following example. SELECT * FROM Customers WHERE CustomerID = ? As a result, the order in which Parameter objects are added to the Parameters collection must directly correspond to the position of the ? placeholder for the parameter. OleDb Example Dim command As OleDbCommand = New OleDbCommand( _
"SampleProc", connection)
command.CommandType = CommandType.StoredProcedure
Dim parameter As OleDbParameter = command.Parameters.Add( _
"RETURN_VALUE", OleDbType.Integer)
parameter.Direction = ParameterDirection.ReturnValue
parameter = command.Parameters.Add( _
"@InputParm", OleDbType.VarChar, 12)
parameter.Value = "Sample Value"
parameter = command.Parameters.Add( _
"@OutputParm", OleDbType.VarChar, 28)
parameter.Direction = ParameterDirection.Output
OleDbCommand command = new OleDbCommand("SampleProc", connection);
command.CommandType = CommandType.StoredProcedure;
OleDbParameter parameter = command.Parameters.Add(
"RETURN_VALUE", OleDbType.Integer);
parameter.Direction = ParameterDirection.ReturnValue;
parameter = command.Parameters.Add(
"@InputParm", OleDbType.VarChar, 12);
parameter.Value = "Sample Value";
parameter = command.Parameters.Add(
"@OutputParm", OleDbType.VarChar, 28);
parameter.Direction = ParameterDirection.Output;
 Odbc Example
Dim command As OdbcCommand = New OdbcCommand( _
"{ ? = CALL SampleProc(?, ?) }", connection)
command.CommandType = CommandType.StoredProcedure
Dim parameter As OdbcParameter = command.Parameters.Add("RETURN_VALUE", OdbcType.Int)
parameter.Direction = ParameterDirection.ReturnValue
parameter = command.Parameters.Add( _
"@InputParm", OdbcType.VarChar, 12)
parameter.Value = "Sample Value"
parameter = command.Parameters.Add( _
"@OutputParm", OdbcType.VarChar, 28)
parameter.Direction = ParameterDirection.Output
OdbcCommand command = new OdbcCommand( _
"{ ? = CALL SampleProc(?, ?) }", connection);
command.CommandType = CommandType.StoredProcedure;
OdbcParameter parameter = command.Parameters.Add( _
"RETURN_VALUE", OdbcType.Int);
parameter.Direction = ParameterDirection.ReturnValue;
parameter = command.Parameters.Add( _
"@InputParm", OdbcType.VarChar, 12);
parameter.Value = "Sample Value";
parameter = command.Parameters.Add( _
"@OutputParm", OdbcType.VarChar, 28);
parameter.Direction = ParameterDirection.Output;
 See Also
Tasks Concepts Other Resources
|
Guia do Desenvolvedor do .NET Framework Trabalhando com parâmetros de comando Os objetos Command usam parâmetros para passar valores para as instruções SQL ou procedimentos armazenados, fornecendo uma verificação de tipo e validação. Ao contrário texto de comando, a entrada de parâmetro é tratada como um valor literal, não como código executável. Isso ajuda na proteção contra ataques "inclusão de SQL", no qual um invasor insere um comando em uma instrução SQL que segurança comprometimentos no servidor. In addition to the Segurança Benefits, parametrizado Commands Provide a método convenient for organizing values passed to a fonte de dados. Um objeto DbParameter pode ser criado usando seu construtor, ou adicionando-lo para o DbParameterCollection chamando o método da coleção AddDbParameterCollection()()(). O método Add terão como entrada uma argumentos de construtor ou um objeto de parâmetro existente, dependendo do provedor de dados.
 Fornecendo a propriedade ParameterDirection
When Adding Parameters, You need to a ParameterDirection for Parameters Outro than Parameters. A tabela a seguir mostra os valores ParameterDirection você pode usar com a enumeração ParameterDirection. | Nome do membro | Descrição | | Input | O parâmetro é um parâmetro de entrada. Este é o padrão. | | InputOutput | The parâmetro is capable of Ambos entrada and saída. | | Output | O parâmetro é um parâmetro de saída. | | ReturnValue | O parâmetro representa um valor de retorno de uma operação como um procedimento armazenado, função interna ou função definida pelo usuário. |
 Trabalhando com espaços reservados de parâmetro
The for Placeholders Depends on the Origem. Os provedores de dados .NET Framework tratar nomeação e especificar parâmetros e espaços reservados de parâmetro de maneira diferente. This sintaxe is tailored to a Specific dados Origem, as described in the seguinte tabela. | Provedor de Dados | Sintaxe de nomeação de parâmetro | | SqlClient | Uses Parâmetros Nomeados in the formato @ParameterName. | | OleDb | Usa os marcadores de parâmetro posicional indicados por um ponto de interrogação (?). | | Odbc | Usa os marcadores de parâmetro posicional indicados por um ponto de interrogação (?). | | OracleClient | Uses Parâmetros Nomeados in the :parmname (or parmname). |
 Especificar tipos de dados de parâmetro
O tipo de dados de um parâmetro é específico para o Provedor de Dados .Net Framework. Especificando o tipo converte o valor do parâmetro para o provedor de dados do.NET Framework tipo antes de passar o valor para o fonte de dados. You May also the tipo of a Parameter in a genérico especificar modo by Configuração the DbType propriedade of the objeto Parameter to a particular DbType. O tipo do provedor de dados do .NET Framework de um objeto Parameter é inferido a partir do tipo .NET Framework do valor do objeto parâmetro ou o DbType do objeto Parameter . A tabela a seguir mostra o inferido Tipo parâmetro baseia o objeto passado como o valor do parâmetro ou o especificado DbType. | Tipo .NET Framework | Sistema. Data.DbType | SqlDbType | OleDbType | OdbcType | OracleType | | bool | Boolean | Bit | Boolean | Bit | Byte | | byte | Byte | TinyInt | UnsignedTinyInt | TinyInt | Byte | | byte[] | Binary | VarBinary. Isso Conversão implícita falhará se a matriz byte é maior do que o tamanho máximo de um VarBinary, que é 8000 bytes.For Arrays byte maior than 8000 bytes, explicitamente Set the SqlDbType. | VarBinary | Binary | Raw | | char | | Não há suporte para inferring um SqlDbType de char. | Char | Char | Byte | | DateTime | DateTime | DateTime | DBTimeStamp | DateTime | DateTime | | Decimal | Decimal | Decimal | Decimal | Numeric | Number | | double | Double | Float | Double | Double | Double | | float | Single | Real | Single | Real | Float | | Guid | Guid | UniqueIdentifier | Guid | UniqueIdentifier | Raw | | Int16 | Int16 | SmallInt | SmallInt | SmallInt | Int16 | | Int32 | Int32 | Int | Int | Int | Int32 | | Int64 | Int64 | BigInt | BigInt | BigInt | Number | | object | Object | Variant | Variant | Não há suporte para inferring um OdbcType de Object. | Blob | | string | String | NVarChar . This implicit conversion will fail if the string is greater than the maximum size of an NVarChar, which is 4000 characters. For Cadeia de caracteres greater than 4000 Characters, Set the SqlDbType. | VarWChar | NVarChar | NVarChar | | TimeSpan | Time | Não há suporte para inferring um SqlDbType de TimeSpan. | DBTime | Time | DateTime | | UInt16 | UInt16 | Não há suporte para inferring um SqlDbType de UInt16. | UnsignedSmallInt | Int | UInt16 | | UInt32 | UInt32 | Não há suporte para inferring um SqlDbType de UInt32. | UnsignedInt | BigInt | UInt32 | | UInt64 | UInt64 | Não há suporte para inferring um SqlDbType de UInt64. | UnsignedBigInt | Numeric | Number | | | AnsiString | VarChar | VarChar | VarChar | VarChar | | | AnsiStringFixedLength | Char | Char | Char | Char | | | Currency | Money | Currency | Não há suporte para inferring um OdbcTypede Currency. | Number | | | Date | Não há suporte para inferring um SqlType de Date. | DBDate | Date | DateTime | | | SByte | Não há suporte para inferring um SqlType de SByte. | TinyInt | Não há suporte para inferring um OdbcTypede SByte. | SByte | | | StringFixedLength | NChar | WChar | NChar | NChar | | | Time | Não há suporte para inferring um SqlType de Time. | DBTime | Time | DateTime | | | VarNumeric | Não há suporte para inferring um SqlDbType de VarNumeric. | VarNumeric | Não há suporte para inferring um OdbcTypede VarNumeric. | Number | Observação: | | Conversions from Decimal to Outro Types are narrowing conversions that the valor Decimal to the nearest toward zero. If the result of the conversão is not representable in the tipo destino, is an OverflowException Descartado. | Observação: | | Quando você envia um valor do parâmetro nulo para o servidor, você deve especificar DBNull, não null (Nothing no Visual Basic). The null value in the system is an empty object that has no value. DBNull is used to represent null values. Para obter mais informações sobre valores Nulos de banco de dados, consulte Manipulação de valores nulos. |
 A derivação de informações de parâmetro
Parâmetros também podem ser derivados de um procedimento armazenado usando a classe DbCommandBuilder. Tanto o SqlCommandBuilderOleDbCommandBuilder classes oferecem um método estático, DeriveParameters, que automaticamente preenche a coleção parâmetros de uma Comando objeto com informações parâmetro de uma procedimento armazenado. Note that DeriveParameters overwrites any existing informações parâmetro for the Comando. Observação: | | Deriving informações parâmetro incurs a penalidade de desempenho because it Requires an Additional processamento to the dados Origem to the informações recuperar. If informações parâmetro is known em tempo de design, you can improve the desempenho of Your aplicativo by configuração the Parâmetros explicitamente. | Para obter mais informações, consulte Gerando comandos automaticamente.
 Usando parâmetros com um SqlCommand e um procedimento armazenado
Stored Procedures Offer muitos Advantages in Applications Data-driven. Using Stored Procedures, banco de dados Operations can be Encapsulated in a single Command, optimized for melhor desempenho, and Enhanced with additional Segurança. Embora um procedimento armazenado pode ser chamado por simplesmente passando o nome de procedimento armazenado seguido pelo parâmetro argumentos como uma instrução SQL, Usando a coleção do objeto do ADO.NET ParametersDbCommand permite que você mais explicitamente definir parâmetros de procedimento armazenado, bem como para acessar parâmetros de saída e retornar valores. Observação: | | Instruções parametrizadas são executadas no servidor usando sp_executesql, que permite a reutilização plano de consulta. Local Cursors or Variables in the sp_executesql are not Visível to the that Calls sp_executesql. Changes in contexto banco de dados Último only to the end of the declaração sp_executesql. For more, see Servidor Books Online. | When Using Parameters with a SqlCommand to executar a SQL Servidor procedimento armazenado, the Names of the Parameters Added to the coleção Parameters must match the Names of the markers parâmetro in the procedimento armazenado. The Provider Data for Servidor does not the (?) for passing Parameters to an Instrução SQL or a . Ele trata os parâmetros no procedimento armazenado como parâmetros nomeados e procura por correspondência marcadores de parâmetros. For exemplo, the CustOrderHist Procedimento Armazenado is defined with a nomeado parâmetro @CustomerID. Quando seu código executa o procedimento armazenado ele também deve usar um parâmetro chamado @CustomerID. CREATE PROCEDURE dbo.CustOrderHist @CustomerID varchar(5) Exemplo Este exemplo demonstra como chamar um SQL Servidor procedimento armazenado no banco de dados exemplo Northwind. O nome do procedimento armazenado é dbo.SalesByCategory e ele possui um parâmetro de entrada chamado @CategoryName com um tipo de dados de nvarchar(15). O código cria um novo SqlConnection dentro de uma usando Bloquear para que a conexão é descartada quando o procedimento termina. O SqlCommand e SqlParameter objetos são criados e defina suas propriedades. Um SqlDataReader executa o SqlCommand e retorna o resultado definidas a partir de procedimento armazenado, exibe a saída na janela do console. Observação: | | Em vez de criar SqlCommandSqlParameter objetos e, em seguida, configuração Propriedades em separar instruções, você pode, em vez disso, optar use um dos construtores sobrecarregados para conjunto múltiplo Propriedades em uma única declaração. | GetSalesByCategory( connectionString , _
categoryName )
connection SqlConnection(connectionString)
command SqlCommand = SqlCommand()
command.Connection = connection
command.CommandText =
command.CommandType = CommandType.StoredProcedure
parameter SqlParameter()
parameter.ParameterName =
parameter.SqlDbType = SqlDbType.NVarChar
parameter.Direction = ParameterDirection.Input
parameter.Value = categoryName
command.Parameters.Add(parameter)
connection.Open()
reader SqlDataReader = command.ExecuteReader()
reader.HasRows
Do reader.Read()
Console.WriteLine(, _
reader(0), reader(1))
Console.WriteLine()
GetSalesByCategory(string connectionString,
string categoryName)
{
(SqlConnection connection = SqlConnection(connectionString))
{
SqlCommand command = SqlCommand();
command.Connection = connection;
command.CommandText = ;
command.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = SqlParameter();
parameter.ParameterName = ;
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
command.Parameters.Add(parameter);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
(reader.HasRows)
{
(reader.Read())
{
Console.WriteLine(, reader[0], reader[1]);
}
}
{
Console.WriteLine();
}
reader.Close();
}
}
 Usando parâmetros com um OleDbCommand ou OdbcCommand
Ao utilizar parâmetros com um OleDbCommand ou OdbcCommand, a ordem dos parâmetros adicionado à coleção Parameters deve corresponder a ordem dos parâmetros definidos em seu procedimento armazenado. The Provider Data .NET Framework for OLE DB and Provider Data .NET Framework for Parameters tratar ODBC in a stored Procedimento as Placeholders and Values parâmetro aplicar in ordem. Além disso, parâmetros valor de retorno devem ser os primeiro parâmetros adicionados à coleção Parameters. O Provedor de Dados .Net Framework para OLE DB e Provedor de Dados .Net Framework para ODBC não suportam parâmetros nomeados para passar parâmetros para uma instrução SQL ou um procedimento armazenado. In this maiúscminúsc, You Must Use the espaço reservado ponto de interrogação (?), as in the seguinte exemplo. SELECT * FROM Customers WHERE CustomerID = ? As a result, the order in which Parameter objects are added to the Parameters collection must directly correspond to the position of the ? placeholder for the parameter. Exemplo OLEDB Dim command As OleDbCommand = New OleDbCommand( _
"SampleProc", connection)
command.CommandType = CommandType.StoredProcedure
Dim parameter As OleDbParameter = command.Parameters.Add( _
"RETURN_VALUE", OleDbType.Integer)
parameter.Direction = ParameterDirection.ReturnValue
parameter = command.Parameters.Add( _
"@InputParm", OleDbType.VarChar, 12)
parameter.Value = "Sample Value"
parameter = command.Parameters.Add( _
"@OutputParm", OleDbType.VarChar, 28)
parameter.Direction = ParameterDirection.Output
OleDbCommand command = new OleDbCommand("SampleProc", connection);
command.CommandType = CommandType.StoredProcedure;
OleDbParameter parameter = command.Parameters.Add(
"RETURN_VALUE", OleDbType.Integer);
parameter.Direction = ParameterDirection.ReturnValue;
parameter = command.Parameters.Add(
"@InputParm", OleDbType.VarChar, 12);
parameter.Value = "Sample Value";
parameter = command.Parameters.Add(
"@OutputParm", OleDbType.VarChar, 28);
parameter.Direction = ParameterDirection.Output;
 Exemplo de ODBC
Dim command As OdbcCommand = New OdbcCommand( _
"{ ? = CALL SampleProc(?, ?) }", connection)
command.CommandType = CommandType.StoredProcedure
Dim parameter As OdbcParameter = command.Parameters.Add("RETURN_VALUE", OdbcType.Int)
parameter.Direction = ParameterDirection.ReturnValue
parameter = command.Parameters.Add( _
"@InputParm", OdbcType.VarChar, 12)
parameter.Value = "Sample Value"
parameter = command.Parameters.Add( _
"@OutputParm", OdbcType.VarChar, 28)
parameter.Direction = ParameterDirection.Output
OdbcCommand command = new OdbcCommand( _
"{ ? = CALL SampleProc(?, ?) }", connection);
command.CommandType = CommandType.StoredProcedure;
OdbcParameter parameter = command.Parameters.Add( _
"RETURN_VALUE", OdbcType.Int);
parameter.Direction = ParameterDirection.ReturnValue;
parameter = command.Parameters.Add( _
"@InputParm", OdbcType.VarChar, 12);
parameter.Value = "Sample Value";
parameter = command.Parameters.Add( _
"@OutputParm", OdbcType.VarChar, 28);
parameter.Direction = ParameterDirection.Output;
 Consulte também
Tarefas Conceitos Outros recursos
|