user1447679
user1447679

Reputation: 3270

SQL Insert Statement - How to specify a condition on a single field

I have a simple form that allows a user to create a service for their business. They can also attach a deal to that service utilizing the same form.

Example:

The are two date fields that are hidden:

  1. ServiceCreated_Date
  2. DealCreated_Date

My question is, since this is form is "inserting" and not updating what would be the proper way to incorporate a condition on the DealCreated_Date?

For example:

INSERT INTO MyTable
(
    ServiceTitle
   ,ServicePrice
   ,ServiceDescription
   ,ServiceCreated_Date
   ,ActivateDeal
   ,DealPrice
   ,DealCreated_Date
) VALUES
(
    @ServiceTitle
   ,@ServicePrice
   ,@ServiceDescription
   ,GETDATE() // For ServiceCreated_Date
   ,@ActivateDeal
   ,@DealPrice
   ,???????

So basically, I want to use GETDATE() for the DealCreated_Date field, but ONLY if ActivateDeal is TRUE (1)

Is there an easy way to do this?

Thank you for your help.

Upvotes: 0

Views: 164

Answers (1)

sgeddes
sgeddes

Reputation: 62861

I think you just want to use a CASE statement:

INSERT INTO MyTable
(
    ServiceTitle
   ,ServicePrice
   ,ServiceDescription
   ,ServiceCreated_Date
   ,ActivateDeal
   ,DealPrice
   ,DealCreated_Date
) VALUES
(
    @ServiceTitle
   ,@ServicePrice
   ,@ServiceDescription
   ,GETDATE() // For ServiceCreated_Date
   ,@ActivateDeal
   ,@DealPrice
   ,CASE WHEN @ActivateDeal THEN getDate() END
)

This should insert the current date or NULL depending on the value of @ActivateDeal. Depending on its datatype, you may need to use CASE WHEN @ActivateDeal = 1 instead.

SQL Fiddle Demo

Upvotes: 2

Related Questions