How can I insert datetime into the SQL Database table ? Is there a way to insert this query through the insert command in C# / .NET?
This question is related to
.net
sql
sql-server
sql-server-2005
c#-3.0
if you got actuall time in mind GETDATE()
would be the function what you looking for
DateTime values should be inserted as if they are strings surrounded by single quotes
'20201231'
but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME)
to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:
CREATE TABLE dbo.T(D DATETIME)
--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')
--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))
You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:
INSERT INTO MyTable (MyDate) Values (GetDate())
If it is not today's date then you should be able to use a string and specify the date format:
INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982
You do not always need to convert the string either, often you can just do something like:
INSERT INTO MyTable (MyDate) Values ('06/26/1982')
And SQL Server will figure it out for you.
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.
Source: Stackoverflow.com