System.Data.SqlClient Namespace SqlCommand Class
Returns the SqlParameterCollection.
Script |
[ SqlParameterCollection variable = ] SqlCommand.Parameters |
variable |
The parameters of the Transact-SQL statement or stored procedure. |
The property is read only with no default value.
The SQL Server™ .NET Data Provider does not support the question mark ( ? ) placeholder for passing parameters to an SQL Statement or a stored procedure called by a Command of CommandType.Text. In this case, named parameters must be used. For example:
SELECT * FROM Customers WHERE CustomerID = @CustomerID
NOTE: If the parameters in the collection do not match the requirements of the query to be executed, an error may result.
For more information see Using Stored Procedures with a Command.
The following example initializes an SqlCommand and displays its parameters. To accomplish this, the method is passed an SqlConnection, a query string that is a Transact-SQL SELECT statement, and an array of SqlParameter objects.
void setSqlCommand ( SqlConnection myConn,
string query, SqlParameter [ ] myParamArray ) {
SqlCommand myCommand = new SqlCommand ( query, myConn );
myCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers " +
"WHERE Country = @Country AND City = @City";
myCommand.Parameters.Add ( myParamArray );
for ( int j = 0; j < myParamArray.Length; j++ ) {
myCommand.Parameters.Add ( myParamArray [ ] );
}
string myMessage = "";
for ( int i = 0; i < myCommand.Parameters.Count; i++ ) {
myMessage += myCommand.Parameters [ ].ToString ( ) + "<br>";
}
Response.Write ( myMessage );
}
Public Sub setSqlCommand ( myConn As SqlConnection, _
query As String, myParamArray ( ) As SqlParameter )
Dim myCommand As New SqlCommand ( query, myConn )
myCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers " & _
"WHERE Country = @Country AND City = @City"
myCommand.Parameters.Add ( myParamArray )
Dim j As Integer
For j = 0 To myCommand.Parameters.Count - 1
myCommand.Parameters.Add ( myParamArray ( j ) )
Next j
Dim myMessage As String = ""
Dim i As Integer
For i = 0 To myCommand.Parameters.Count - 1
myMessage += myCommand.Parameters ( i ).ToString ( ) & ControlChars.Cr
Next i
Response.Write ( myMessage )
End Sub |
|
C# |
VB |
SqlCommand Members SqlParameter