Passing Variables to sql command text-Newbe

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

Hello,
How do I pass variables to a command text.(C#)Because of the quotes,it
seems that the values are not passed.
Thanks,
Mike
 
Hi Mike,
are you using a stored procedure or creating dynamic sql? If you are
using a stored procedure and using SQL Srver you can do something like:

SqlCommand command = new SqlCommand();
command.CommandText = "myStoredProcedureName";

//set the connection object
command.Connection = objConn;
command.CommandType = System.Data.CommandType.StoredProcedure;

//create parameter and add it to the command
SqlParameter param = new SqlParameter("@UserName",
System.Data.SqlDbType.VarChar, 30);
command.Parameters.Add(param);


If you are writing dynamic SQL then you could do something like:

string sqlCommand = "Select * from tblX WHERE UserName='" + userName + "'"
SqlCommand command = new SqlCommand(sqlCommand, objConn);

Hope that helps
Mark R Dawson
 
Back
Top