-4

隨着SQL數據庫在Visual Studio 2012年數學運算2表中的SQL

但我不知道如何使他們有一個自動的數學運算。的情況下: 有3表中的datagridview:

  1. 薪水
  2. salary_Overtime
  3. salary_cuts

總計=(工資+ salary_overtime) - salary_cuts

我已經在這裏編寫了一些編碼,但是當我保存一個新的數據時它沒有影響。我問我的朋友,他說你應該添加新的觸發器。

==工資== Salary_Overtime == Salary_Cuts == ==總

== 5000 == 2000 == 1000 == == 6000

+0

請添加相關列,例如數據,預期產出和你被卡住查詢。 –

回答

0

您可以在SQL Server中使用Computed Column來執行您正在嘗試執行的操作。

在一個表中指定計算列:

計算列是未物理地存儲在 該表中,除非列標記PERSISTED一個虛擬列。計算列 表達式可以使用來自其他列的數據來計算其所屬列的值。您可以使用SQL Server Management Studio或Transact-SQL爲SQL Server 2016中的 計算列指定一個表達式。

所以下面是一個例子。注意Total列包含計算,所以當你查詢表,將計算出的價值爲您提供:

CREATE TABLE #Salary 
    (
     salary INT , 
     salary_overtime INT , 
     salary_cuts INT , 
     Total AS (salary + salary_overtime) - salary_cuts 
    ); 

-- Insert values into the table. 
INSERT INTO #Salary 
     (salary , 
      salary_overtime , 
      salary_cuts 
     ) 
VALUES (5000 , 
      2000 , 
      1000 
     ) 

SELECT * 
FROM #Salary 

-- Produces: 
--salary salary_overtime salary_cuts Total 
--5000  2000   1000  6000 

-- After an UPDATE: 
UPDATE #Salary 
SET  salary_cuts = 2000 

SELECT * 
FROM #Salary 

-- Produces: 
-- salary salary_overtime salary_cuts Total 
-- 5000  2000   2000  5000 

DROP TABLE #Salary