从参考表更新值

时间:2014-07-02 11:16:32

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我正在使用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

如何为上述场景编写更新查询?

1 个答案:

答案 0 :(得分: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