views:

231

answers:

3
+4  Q: 

# in SQL Query

I have somebody elses code (C# ASP.Net) which contains the following query:

string query = "SELECT distinct(destinations.name) as Destinations 
                FROM destinations, flights 
                WHERE destinations.d_ID = flights.d_ID 
                  AND flights.Date = #" + date.ToShortDateString() + "#";

I could not find why the # is required here before and after the date parameter. It could be passed as a normal string value (between ' and '). Is there any advantage of using # ?

Many Thanks, Ali

+3  A: 

That is access syntax, are you sure you are connecting to sql server?

SQLMenace
+6  A: 

Is this against an access database? That platform requires dates be bracketed by the "#"

Edit: to answer your main question, no, unless it is Access where it would be required, there is no benefit of leaving the hash marks in the query as is.

curtisk
+1 for explaining the syntax.
sheepsimulator
The # is not *required* for the Access database engine. For example, rather than using the DATETIME literal #7/1/2009#, you could use the text literal '2009-07-01' which would be implicitly coerced to DATETIME when evaluated. The advantage of using text is to avoid Access changing the local short date format to US (ambiguous) format.
onedaywhen
+9  A: 

There is nothing wrong with the pound symbol, but it is not ANSI compliant SQL. You are much better off rewriting the query with a parameter for the date.

ex:

SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT distinct(destinations.name) as Destinations FROM destinations, flights WHERE destinations.d_ID = flights.d_ID AND flights.Date = @dateparm";
cmd.Parameters.Add(new SqlParameter("dateparm",value);
SqlDataReader rdr = cmd.ExecuteReader();
jle
+1, the pound signs aren't the problem, it's the concatination that's the problem. One thing to note: SqlClient supports named parameters, other clients may not.
Michael Meadows