1

I realise this question has been asked before, but after going through the previously answered questions, i still can't quite figure out what's wrong with this code.

FYI I am in the UK.

   public static void GetDataForCSEP(string viewName, string schemaName, 
                                             string dateFieldName, DateTime startDate, DateTime endDate)
        {

            string dateFormat = "yyyy/MM/dd HH:mm:ss";


            //Connect to SQl Server 

            string commandText = "SELECT * FROM " + schemaName + "." + viewName + " WHERE @dateFieldName BETWEEN @startDate AND  @endDate";


            using (SqlCommand sqlCmd = new SqlCommand(commandText,sql_Conn))
            {
                sqlCmd.CommandType = CommandType.Text;

                sqlCmd.Parameters.Add("@dateFieldName",SqlDbType.NVarChar, 30).Value = dateFieldName;
                sqlCmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = DateTime.Parse(startDate.ToString(dateFormat));
                sqlCmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = DateTime.Parse(startDate.ToString(dateFormat));



                sql_Conn.Open();
                sqlCmd.ExecuteNonQuery();


            }
}
2
  • 1
    Why on earth are you doing DateTime.Parse(startDate.ToString(dateFormat)) - startDate is already a DateTime value. Why convert it to string just to convert it back? Commented Jul 26, 2011 at 13:33
  • Because i'm a rubbish programmer:) Commented Jul 26, 2011 at 13:38

2 Answers 2

2

On Error is you cannot pass column name as parameter

    "SELECT * FROM " + schemaName + "." + viewName + " 
WHERE @dateFieldName BETWEEN @startDate AND  @endDate";

this should be

    "SELECT * FROM " + schemaName + "." + viewName + " 
WHERE " + dateFieldName  + " BETWEEN @startDate AND  @endDate";

To avoid sqlInjection attack make use of Sp_executeSQL to execute this type of query, because this is dynamic sql query.

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed, as structured the code will attempt to check whether the Static String @dateFieldName is between two dates. To do this the SQL Engine is attempting to convert the text value of @dateFieldName into a date, and failing.
1

It will depend on your SQL Server locale settings, but perhaps

string dateFormat = "dd-MMM-yyyy HH:mm:ss";

will work for you?

2 Comments

THanks, how do i find out those settings? It's login specific isn't it?
Yes and no - there'll be defaults, but you can also modify them for the duration of a user's connection etc. I'd check Books Online, as I'm not so familiar with the DBA side!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.