表SQL中两列的总和

时间:2018-10-01 12:01:06

标签: sql sql-server

我的任务是除P_Key和F_key外,我还有三列Stock_OpeningStock_NewStock_Available。我必须在Stock_New中插入一些值。然后Stock_Opening + Stock_New将加起来,值将进入Stock_Available

问题:当我在Stock_New中插入一个值并执行时,只会更新Stock_New 如果我再次执行相同的查询,则现在将两个表Stock_New更新为当前  值和Stock_Available与先前的值。 我希望Stock_NewStock_Available同时更新 波纹管是我正在执行的查询

UPDATE Stock
SET Stock_New = Stock_New + '2',
    Stock_Available = Stock_Opening + Stock_New
WHERE Med_ID = 'PANAD223'

下面是线性截图

This is the table before execution

This is the table after first execution

This is the table after second execution

8 个答案:

答案 0 :(得分:1)

Stock_New完成后,

update将更新为最新值。试试:

UPDATE Stock SET Stock_New = Stock_New + 2 , Stock_Available = Stock_Opening + Stock_New+2 WHERE Med_ID='PANAD223'

答案 1 :(得分:1)

如果您引用UPDATE中的一列,则会在UPDATE之前之前获得值。因此Stock_NewStock_Available = Stock_Opening + Stock_New总是两个短。您还需要在其中添加2

UPDATE stock
       SET stock_new = stock_new + 2,
           stock_available = stock_opening + stock_new + 2
       WHERE med_id = 'PANAD223';

此外,如果您有数字文字,请不要将其用单引号引起来。那是字符串。

答案 2 :(得分:0)

请尝试如下更新:

UPDATE Stock SET Stock_New = Stock_New + '2', Stock_Available = Stock_Opening + Stock_New + '2' WHERE Med_ID='PANAD223'

答案 3 :(得分:0)

据我所知,计算列适合您的情况。

  

计算列实际上是在物理上不是虚拟列   除非该列标记为PERSISTED,否则存储在表中。的价值   每次在列中引用计算列时都会重新计算   查询

请参阅https://www.c-sharpcorner.com/article/computed-columns-in-sql-server/

答案 4 :(得分:0)

数据更新1时,Stock_New = 28,Stock_Opening = 20

UPDATE Stock SET Stock_New = 28 + '2', 
                 Stock_Available = 20 + 28
 WHERE Med_ID='PANAD223'

数据更新2时,Stock_New = 30,Stock_Opening = 20

UPDATE Stock SET Stock_New = 28 + '2', 
                 Stock_Available = 20 + 30
 WHERE Med_ID='PANAD223'

因此您将(+'2')添加到

UPDATE Stock SET Stock_New = Stock_New + '2', 
                 Stock_Available = Stock_Opening + Stock_New + '2'
 WHERE Med_ID='PANAD223'

答案 5 :(得分:0)

create proc sampleupdate
as
begin
declare @stocknew int,
declare @stockopening int 

set @stocknew=(select Stock_New from Stock (condition))
set @stockopening=(select Stock_Opening  from Stock (condition))

set @stocknew=@stocknew +'2'
UPDATE Stock SET Stock_New =@sn, Stock_Available = @stockopening + @sn WHERE 
Med_ID='PANAD223'
end

答案 6 :(得分:0)

您可以使用stock_available = stock_opening + stock_new + 2,因为SQL会计算第一个值,而不是更新的值。

一种更简单的方法是创建由其他两列计算得出的Stock_Available列:

ALTER TABLE Stock
DROP COLUMN Stock_Available

ALTER TABLE Stock
ADD Stock_Available AS Stock_New + Stock_Opening

现在您只需要进行更新:

UPDATE Stock Set Stock_New = Stock_New + 2 WHERE Med_ID='PANAD223'

并且Stock_Available将自动更新

答案 7 :(得分:0)

尝试在您为Stock_New分配新值的同一Update语句中计算Stock_Available字段,它将使用Stock_New的存储值而不是计算(更新)的值。因此,Stock_Available将始终比其应有的少2。您可以像其他人回答的那样向Stock_Available计算中添加+2,也可以运行两个单独的Update语句。

更新语句1设置新的Stock_New值:

UPDATE Stock
SET Stock_New = Stock_New + 2
WHERE Med_ID = 'PANAD223';

一旦Stock_New具有新值,请使用该新值来计算Stock_Available:

UPDATE Stock
SET Stock_Available = Stock_Opening + Stock_New
WHERE Med_ID = 'PANAD223'