0

How to convert a C# DateTime variable into Enum of SqlDataType.DateTime?

How to consume that enum into a connection string?

Is doing something like this correct?

string str = "SELECT * FROM TABLE WHERE CreateDt " + <that enum>;
SqlConnection Connection = new SqlConnection (<connection setting>);
Table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);

Thank you

2 Answers 2

3

Your best option is to use a parameterized command:

            var cmd = new SqlCommand();
            cmd.Connection = conn;

            DateTime MyDate = DateTime.Now;

            cmd.CommandText = @"SELECT * FROM TABLE WHERE CreateDt = @MyDate";
            cmd.Parameters.AddWithValue("@MyDate", @MyDate);

            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            adapter.FillSchema(Table, SchemaType.Source);
            adapter.Fill(Table);
Sign up to request clarification or add additional context in comments.

6 Comments

is this command text allows alteration for example doing sth like cmd.CommandText += "AND FinishDt = @MyDate";
if i use Command Text, how shall I fill a datatable using that connection? (like the 1 I use show in my question)
Sorry, I was getting the correct syntax for that. I have updated the answer.
I receive sqldatetime overflow error when i test this code, any idea how it happen?
This will definitely happen if the date/time you are passing has not been set to a valid value. This is because in this case, the DateTime parameter will default to DateTime.MinValue (1/1/0001), which is far below the allowable minimum in SQL Server, which is 1/1/1753.
|
1

This is not tested, but how about:

string str = "SELECT * FROM TABLE WHERE CreateDt = @createDate";

SqlConnection Connection = new SqlConnection (<connection setting>);

Table mytable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);

adapter .SelectCommand.Parameters.Add("@createDate", SqlDbType.DateTime)
adapter .SelectCommand.Parameters("@createDate").Value = <Some DateTime>

adapter.FillSchema(mytable, SchemaType.Source);
adapter.Fill(Table);

Comments

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.