Two small issues, mostly concerning the @AT syntax when dealing with data in ASP.Net (C#). Most online tutorials show a lot of this following type of code but fail to mention (or I may have overlooked) the actual purpose of the ampersand although they do explain the general purpose of the code. In this example, just querying the database to get data pertaining to a certain month for a calender control.
protected DataSet GetCurrentMonthData(DateTime firstDate,
DateTime lastDate)
{
DataSet dsMonth = new DataSet();
ConnectionStringSettings cs;
cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
String connString = cs.ConnectionString;
SqlConnection dbConnection = new SqlConnection(connString);
String query;
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= @firstDate AND HolidayDate < @lastDate";
SqlCommand dbCommand = new SqlCommand(query, dbConnection);
dbCommand.Parameters.Add(new SqlParameter("@firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("@lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
try
{
sqlDataAdapter.Fill(dsMonth);
}
catch {}
return dsMonth;
}
First issue: What do @firstDate and @lastDate mean or reference in the database string query? Is that referencing the parameters being passed in GetCurrentMonthData method or the actual column name in the database table ?
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= @firstDate AND HolidayDate < @lastDate";
Second issue: What is the difference between @firstDate and firstDate? Am I correct in saying firstDate is the actual parameter variable itself?
dbCommand.Parameters.Add(new SqlParameter("@firstDate",
firstDate));
I agree with @har07. That is not a ampersand. An ampersand, as far as I know, looks like this -> &
. To answer the question, the 'at' sign
(@) is used to indicate variables in a parameterized query in c#.
In the code
dbCommand.Parameters.Add(new SqlParameter("@firstDate",firstDate));
you are assigning the value of the DateTime variable firstDate
to the @firstDate
variable in your query.
Here's an example that's a bit less confusing(I hope):
Let's say I have a string variable called myName
and I want to pass that to my query select * from students where name = @name
.
To pass the value of myName
to @name
in my query, I would do
dbCommand.Parameters.Add(new SqlParameter("@name",myName));
I hope that helps.