title: insert if not exists in sql
body: <p>I am using ms visual studio 2012 and ms sql 2012.</p>
  
  <p>On my asp.net VB page I have a 4 text boxes that a user can enter values and click insert.  These values are then passed along with the date, users name and an integer to sql via subroutine that does the first text box value then the second and so on.</p>
  
  <p>My problem is with the stored procedure.  I used an IF NOT exist to look at the current data in the table and if there is no data matching the date and the integer then it will insert the record.   The VB sub will then pass the second group of data in and it will again look to see if the date is there along with the integer and so on.  The stored procedure is as follows:</p>
  
  <pre><code>@price money,
  @datesubmitted datetime,
  @commodityID int,
  @submitted_By nvarchar(10)
  
  As
      begin
      if not exists ((select * from dailyPricing where (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 1)
      or
      (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 2)
      or
      (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 3)
      or
      (convert(date, datesubmitted, 103) = convert(date, @datesubmitted, 103) and commodityID = 4)))
      Begin
      INSERT INTO dailyPricing (price, datesubmitted, commodityID, submitted_By)
      values(@price, @datesubmitted, @commodityID, @submitted_By)
  
  end
  end
  </code></pre>
  
  <p>The result of the above is that it only enters the first group of values and not the second, third or fourth.  I have debugged my VB code and it is working correctly I just think I haven't formed the SQL correctly.</p>