What is the "@" for?

  • Thread starter Thread starter Jason Huang
  • Start date Start date
J

Jason Huang

Hi,

Would someone tell me what's the "@" for in the folloing code?

SqlCommand cmd = new SqlCommand( "SELECT * FROM Products WHERE ProductID
= @ProductID", con("Server=localhost; DataBase=Northwind; uid=YY;
password=XXXXXX"));

Thanks a lot.

Jason
 
Jason Huang said:
Hi,

Would someone tell me what's the "@" for in the folloing code?

SqlCommand cmd = new SqlCommand( "SELECT * FROM Products WHERE ProductID
= @ProductID", con("Server=localhost; DataBase=Northwind; uid=YY;
password=XXXXXX"));

It designates that you want the SQL parameter or variable ProductID, in this
case, instead of the database field ProductID. Basically, variables and
parameters are prefixed by @, in TSQL atleast, although I'm not sure if it
is required in the standard, or if it is TSQL specific, or just common
naming.

A little further on in the code you should see code adding the parameter to
the command.
 
hi,

where you got that query from?
I bet it was from a stored procedure, if that is so you cannot use it from
C# and ADO.NET you have to use ? instead
and remember to add the value to the Parameters collection.

google this: "parameterized queries" site:msdn.microsoft.com

cheers,
 
You can use the "@" syntax if you want. This works fine:
private void frmOptions_Load(object sender, System.EventArgs e)
{
sc2.CommandText = "Select Top 1 OptionType From MU_Options Where
OptionName = @OptionName";
sc2.Connection=cn;
sc2.Parameters.Add("@OptionName", SqlDbType.VarChar, 50);

cn.Open();
sc2.Parameters["@OptionName"].Value = cbOption.Text;
SqlDataReader dr = sc2.ExecuteReader();
if (dr.HasRows){
dr.Read(
{
cbOptType.Text = (dr["OptionType"].ToString());
}
dr.Close();
cn.Close();
}
}

Works fine calling Stored Procedures as well

Bob Graham
 
Back
Top