Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert data to table when one of the columns is set to current timestamp on insert?

I have a date column of type datetime and I want it to update to the current date and time on every insert.

I set the column to Default Value or Binding = (getdate())

But still, the code itself throws an error about it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Must declare the scalar variable "@date".

This is the query:

SqlCommand SQLCmd = new SqlCommand("INSERT INTO table VALUES(@name, @phone, @date)", SQLCon);
SQLCmd.Parameters.AddWithValue("@name", name);
SQLCmd.Parameters.AddWithValue("@phone", phone);

I also tried to completely omit @date:

SqlCommand SQLCmd = new SqlCommand("INSERT INTO table VALUES(@name, @phone)", SQLCon);

But then I get this error:

Column name or number of supplied values does not match table definition.

When I changed the id column to identity, it stopped asking me to declare the scalar variable @id, but that didn’t help with the date column.

>Solution :

In SQL Server, when you want to insert a row but only fill specific columns, you need to tell which columns:

INSERT INTO table (NAME, PHONE) -- <- tell which columns
VALUES (@name, @phone)

If you don’t do this, there is no way it can magically guess what value goes in which column

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading