2

I want to insert DateTime variable into database table column of DateTime2 type (from .net program) (im using sqlServer 2008, .net 4.0, c#)

now I have

     string insertCommand = @"INSERT INTO X VALUES (time.ToString());

Problem is in time string format. SQL Server does not work with output from ToString() function. I also tried .ToLongDate short date etc.. How to create proper sql command and how to format dateTime string to make this work?

3 Answers 3

2

Try this:

string sql = "insert into x values (@dt)";
SqlCommand cmd = cxn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@dt", time);
cmd.CommandText = sql;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
Sign up to request clarification or add additional context in comments.

1 Comment

Considering time as datetime of C#, when I do the same, only the date is stored in the database and not the timestamp. Why is that ?
1

You need to add a parameter with your DateTime value.

Comments

0

not confirm but you can use use format times.tostring("dd/MMM/yyyy") like http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

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.