Search code examples
sql-servervb.netdatedateadd

Updating a value to have 2 days infront of the previous date in SQL


I have a table called FireTest my standard insert into this table is :

    Dim ThisDay As Date = Date.Today
    connection.Open()
    command = New SqlCommand("Insert Into FireTest([Date],[Type],[Comments],[Completed By],[Trans Type]) Values (@Date,@Type,@Comments,@CompletedBy, @TransType)", connection)
    command.Parameters.AddWithValue("@Date", ThisDay)
    command.Parameters.AddWithValue("@Type", DropDownList1.SelectedValue)
    command.Parameters.AddWithValue("@Comments", TextBox1.Text)
    command.Parameters.AddWithValue("@CompletedBy", ThisUser)
    command.Parameters.AddWithValue("@TransType", transType)
    command.ExecuteNonQuery()
    connection.Close()

So i add a new column into the SQL TABLE making the new insert

      Dim ThisDay As Date = Date.Today
      connection.Open()
    command = New SqlCommand("Insert Into FireTest([Date],[Due Date],[Type],[Comments],[Completed By],[Trans Type]) Values (@Date,@DueDate,@Type,@Comments,@CompletedBy, @TransType)", connection)
    command.Parameters.AddWithValue("@Date", ThisDay)
    command.Parameters.AddwithValue("@DueDate",???)
    command.Parameters.AddWithValue("@Type", DropDownList1.SelectedValue)
    command.Parameters.AddWithValue("@Comments", TextBox1.Text)
    command.Parameters.AddWithValue("@CompletedBy", ThisUser)
    command.Parameters.AddWithValue("@TransType", transType)
    command.ExecuteNonQuery()
    connection.Close()

How would I insert the value of this into the database but with a +2 days onto the ThisDay? Example : If ThisDay = '22/04/2014' then the value of @DueDate will be '24/04/2014' I know it has something to do with something along the lines of DATEADD but I'm not sure , any guidance around to help me achieve this?


Solution

  • Every DateTime object has a set of methods to use for this kind of calcs.

    In your case you need the DateTime.AddDays(numberOfDays)

     command.Parameters.AddwithValue("@DueDate",ThisDay.AddDays(2)));
    

    This will add 2 days at the value of ThisDay and creates a new DateTime that you pass as parameter for the @DueDate. Despite its name you should use this method also if you want to subtract days from the current date. In this case the value passed should be negative.