Insert server date and time using SqlCommand
I have a SqlCommand that inserts a datetime into a column using SqlParameter. I am currently using DateTime.Now as the value for this parameter.
I suppose this will add the datetime on the user's PC, which is inconsistent.
How do I change this to insert the date and time of the database server?
EDIT:
I had to make it clear that it was for inserts only
source to share
Is it strictly for INSERT? Or for updates?
If it's for INSERT only, you can declare a DEFAULT constraint on the DATETIME column on the SQL Server side and then just not insert the value from the client side - thus using the default server.
In SQL:
ALTER TABLE YourTable
ADD CONSTRAINT DF_YourTable_YourColumn
DEFAULT (GETDATE()) FOR YourColumn
and then in your SQL command just don't mention "Column" and don't specify its value - the server will use getdate()
to get the current date / time on the server.
Mark
source to share
You can use stored procedure and GETDATE (),
tableName (none: int, name: varchar (40), date and time)
Stored procedure
CREATE PROCEDURE AddRec
@no int,
@name varchar(40)
AS
insert into tableName
values (@no,@name,getdate())
RETURN
Code to execute a stored procedure
SqlConnection cn=new SqlConnection("Your_Cn_Str");
SqlCommand cmd=new SqlCommand();
cmd.CommandText="AddRec";
cmd.CommandType=CommandType.StoredProcedue;
cmd.Connection=cn;
cmd.Parameters.AddWithValue("@no",10);
cmd.Parameters.AddWithValue("@name","Foo");
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
source to share