简体   繁体   中英

insert if not exists in sql

I am using ms visual studio 2012 and ms sql 2012.

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.

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:

@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

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.

I think you need to rewrite that "not exists" for every check try something like this, and i think you need to update the brackets they might be wrong:

if not exists ((select * from dailyPricing where 
  (convert(date, datesubmitted, 103)
     = convert(date, @datesubmitted, 103) and commodityID = 1)

or

if not exists ((select * from dailyPricing where 
   (convert(date, datesubmitted, 103) 
     = convert(date, @datesubmitted, 103) and commodityID = 2)

or ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM