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.

6
  • try cmd.Parameters.AddWithValue("@doj", DateTime.Now); Commented Aug 23, 2015 at 15:56
  • For storing date in database use better DATETIME. TIMESTAMP has different usage. Commented Aug 23, 2015 at 15:57
  • 1
    Is there a reason you are using timestamp? That is used for versioning, not for storing a date/time value. Commented Aug 23, 2015 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 Commented Aug 23, 2015 at 16:03
  • Explicitly name columns in INSERT INTO user3 (uname, email, doj) VALUES (@uname, @email,@doj) Commented Aug 23, 2015 at 16:06

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Or datetime2 is better and recommended for new work.
Changing datatype is not all, for full solution look how parameters are binded.
Thanks @Iad2025. I saw that parameter just now.
Don't fix code inside the question. That's what answers are for.
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.

Comments

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?

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.