How to insert datetime into SQL Database table?

How to insert date and time into SQL database table? Is there a way to insert this request through the insert command in C # /. NET?

+63
sql sql-server sql-server-2005
Mar 13 '11 at 4:27
source share
4 answers

DateTime values ​​should be inserted as if they were strings surrounded by single quotes:

'20100301' 

SQL Server allows you to use many accepted date formats, and in most cases, development libraries provide a number of classes or functions to correctly enter date and time values. However, if you do this manually, it is important to distinguish between the date format using DateFormat and use a generic format:

 Set DateFormat MDY --indicates the general format is Month Day Year Insert Table( DateTImeCol ) Values( '2011-03-12' ) 

By setting the date format, SQL Server now assumes that my format is YYYY-MM-DD instead of YYYY-DD-MM .

SET DATEFORMAT

SQL Server also recognizes a common format that is always interpreted the same way: YYYYMMDD for example. 20110312 .

If you are asking how to insert the current date and time using T-SQL, I would recommend using the keyword CURRENT_TIMESTAMP . For example:

 Insert Table( DateTimeCol ) Values( CURRENT_TIMESTAMP ) 
+101
Mar 13 2018-11-11T00:
source share

You will need to have a datetime column in the table. You can then insert the following insert to insert the current date:

 INSERT INTO MyTable (MyDate) Values (GetDate()) 

If this is not today's date, you should use a string and specify the date format :

 INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982 

You don't always need to convert the string, often you can just do something like:

 INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

+14
Mar 13 2018-11-11T00:
source share

if you have time in mind GETDATE() will be the function you are looking for

+8
Mar 13 '11 at 4:30
source share
 myConn.Execute "INSERT INTO DayTr (dtID, DTSuID, DTDaTi, DTGrKg) VALUES (" & Val(txtTrNo) & "," & Val(txtCID) & ", '" & Format(txtTrDate, "yyyy-mm-dd") & "' ," & Val(Format(txtGross, "######0.00")) & ")" 

Done in vb with all text type variables.

-one
Jan 20 '13 at 17:49
source share



All Articles