0

我與SQL Server 2008中我有兩個表和一個參考table.table1包含工作,更新值從參考表

 Id Name test1 test2 
     1 sss started processing 
     2 asdfasd started processing 

表2列出,

 Id Name test1 test2 
     1 sss  2  2 
     2 asdfasd 3  2 

參考表有,

 code Name 
     1 Started 
     2 processing 
     3 stopped 

我必須寫更新查詢改變表2的值作爲以下,

 Id Name test1 test2 
     1 sss  1  2 
     2 asdfasd 1  2 

如何爲上述場景編寫更新查詢?

+0

,你需要更新表2? – Jesuraja

回答

1

請在下面找到示例。

您可以根據表1的數據做一個UPDATE

DECLARE @table1 Table (ID INT, NAME VARCHAR(100), test1 VARCHAR(100), test2 VARCHAR(100)) 

INSERT INTO @table1 SELECT 1, 'sss', 'started', 'processing' 
INSERT INTO @table1 SELECT 2, 'asdfasd', 'started', 'processing' 

DECLARE @table2 Table (ID INT, NAME VARCHAR(100), test1 INT, test2 INT) 

INSERT INTO @table2 SELECT 1, 'sss', 2, 2 
INSERT INTO @table2 SELECT 2, 'asdfasd', 3, 2 

DECLARE @refTable Table (CODE INT, NAME VARCHAR(100)) 

INSERT INTO @refTable SELECT 1, 'Started' 
INSERT INTO @refTable SELECT 2, 'processing' 
INSERT INTO @refTable SELECT 3, 'stopped' 


UPDATE T2 
SET test1 = R1.Code, 
    test2 = R2.Code 
FROM @table2 T2 
INNER JOIN @table1 T1 
    ON T1.ID = T2.ID 
INNER JOIN @refTable R1 
    ON T1.test1 = R1.Name 
INNER JOIN @refTable R2 
    ON T1.test2 = R2.Name 

SELECT * 
FROM @table2