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

Issue

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:

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



Answered By - Rafalon
Answer Checked By - Robin (sql.easybugfix Admin)

Related Posts

Post a Comment