NEVER use string concatenation to build a SQL query.
ALWAYS use a parameterized query.
Whilst
in this particular instance you're probably safe, since the values have been parsed to
DateTime
s, concatenating values into your queries can and will leave you vulnerable to
SQL Injection[
^].
It will also pollute your DBMSs plan cache, since every query is different. Unless your server has an option to
"optimise for ad-hoc workflows" or similar, you will end up with a cache full of plans for variants of this one query, rather than one cached plan for the parameterized version of the query.
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM table_z WHERE TRUNC(DT) >= @FromDate AND TRUNC(DT) <= @ToDate";
command.Parameters.AddWithValue("@FromDate", DTFromDate);
command.Parameters.AddWithValue("@ToDate", DTToDate);
...
}
Once you've got that working, you'll want to reconsider how you construct your query. Calling a function on a column in the
WHERE
clause will not be
SARGable[
^], so your query will never be able to use an index on the
DT
column.