简体   繁体   English

如果SQL中不存在则插入

[英]insert if not exists in sql

I am using ms visual studio 2012 and ms sql 2012. 我正在使用MS Visual Studio 2012和MS SQL 2012。

On my asp.net VB page I have a 4 text boxes that a user can enter values and click insert. 在我的asp.net VB页面上,我有4个文本框,用户可以输入值并单击插入。 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. 然后,这些值与日期,用户名和一个整数一起通过子例程传递给sql,该子例程执行第一个文本框值,然后执行第二个文本框值,依此类推。

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. 我使用IF NOT不存在查看表中的当前数据,如果没有与日期和整数匹配的数据,它将插入记录。 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. 然后,VB子将传入第二组数据,并再次查看日期是否与整数一起出现,依此类推。 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. 我已经调试了我的VB代码,它可以正常工作,我只是认为我没有正确形成SQL。

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 .... 要么 ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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