0

I want to insert current date and time into sql server database from asp.net webpage. I am using timestamp datatype in sql server table.

table structure:

CREATE TABLE user3
  (
     uname VARCHAR(50) PRIMARY KEY,
     email VARCHAR(50),
     doj   TIMESTAMP
  ); 

code used :

   cmd.Parameters.Clear();
        cmd.CommandText = "insert into user3 values(@uname,@email,@doj)";
        cmd.Parameters.AddWithValue("@uname", uname);           
        cmd.Parameters.AddWithValue("@email", email);   
        cmd.Parameters.AddWithValue("@jdate", DateTime.Now);
        if (cn.State == ConnectionState.Closed)
            cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();

Please Help me with your suggestions and solutions.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
dheena
  • 85
  • 3
  • 6
  • 15
  • try `cmd.Parameters.AddWithValue("@doj", DateTime.Now);` – A_Sk Aug 23 '15 at 15:56
  • For storing date in database use better [DATETIME](http://stackoverflow.com/questions/7105093/difference-between-datetime-and-timestamp-in-sqlserver). TIMESTAMP has different usage. – Lukasz Szozda Aug 23 '15 at 15:57
  • 1
    Is there a reason you are using timestamp? That is used for versioning, not for storing a date/time value. – TTeeple Aug 23 '15 at 15:58
  • If the value will only ever be set once (as join date will), set the column in the database to have a default value – Mark Tickner Aug 23 '15 at 16:03
  • Explicitly name columns in `INSERT INTO user3 (uname, email, doj) VALUES (@uname, @email,@doj)` – Lukasz Szozda Aug 23 '15 at 16:06
  • Another solution do not pass date at all, create INSERT and UPDATE trigger to automatically set date. – Lukasz Szozda Aug 23 '15 at 16:13

3 Answers3

2

Timestamp is method for row versioning. It is automatically generated. But datetime is a datatype. So use datetime instead of timestamp.

create table user3(uname varchar(50) primary key,email varchar(50),doj datetime);
Sailesh Babu Doppalapudi
  • 1,534
  • 1
  • 10
  • 22
1

Use datetime with a default value:

create table user3 (
    uname varchar(50) primary key,
    email varchar(50),
    doj datetime default getdate()
   );

When you insert a new row into the table -- with no value for doj -- then it will get set automatically. I usually called this column CreatedAt.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Assuming it's the case that you are making an insert every time a user signs up;

Try setting a constraint on the table

create table user3(uname varchar(50) primary key,email varchar(50),doj datetime default getdate());

Then you won't have to pass in that value each time

SQL Server default date time stamp?

Community
  • 1
  • 1
Fin
  • 173
  • 1
  • 6