如果存在,则查询不能正常工作

cod*_*ior 1 sql sql-server sql-server-2008

If exists
(select @item from Table_RestaurantsTransaction
where Mobile=@mobile and OrderPlaced=0 and Restaurant=@restaurantName ) 

begin

update Table_RestaurantsTransaction
set Quantity+=@quantity
where Item=@item and Mobile=@mobile and OrderPlaced=0 and Restaurant=@restaurantName

end

else

begin

insert into Table_RestaurantsTransaction(Mobile,TransactionID,Item,Price,DecisionStatus,OrderPlaced,TransactionDate,Restaurant,Quantity)
values(@mobile,@transactionID,@item,@price,1,0,GETDATE(),@restaurantName,@quantity)


end
end
Run Code Online (Sandbox Code Playgroud)

在上面的查询中,插入查询仅在我添加项目时第一次执行.然后,如果我添加相同的项目,则会执行更新查询.但是如果我尝试添加新项,则不会执行insert子句中的插入查询.

请告诉我的错误.

Gor*_*off 7

我想你想测试if子句中项目的存在:

If exists (select 1
           from Table_RestaurantsTransaction
           where item = @item and Mobile=@mobile and OrderPlaced=0 and Restaurant=@restaurantName
          ) 
. . .
Run Code Online (Sandbox Code Playgroud)

但是,您应该merge在一个语句中了解完成此操作的语句.