如何用多列条件更新表?

时间:2019-01-02 12:31:20

标签: sql sql-server tsql sql-server-2012

我正在尝试从另一个数据库的表中获取结果。

我的代码是

Declare @customer table (name, custno, address)

Insert into @customer (custno, address)
values (1, Madrid)

Declare @account table (custno, accno, accbalance)

Insert into @account (custno, accno)
values (1, 2)

Declare @transaction table (accno, accbalance, address)

Insert into @transaction (accno, amount)
values (2, 2)

现在我要设置

@transaction.address = @customer.address

我仍然找不到解决方法。

我希望在

时输出
select * from @transaction 

结果是

2 | 2 | Madrid

4 个答案:

答案 0 :(得分:0)

我认为thises查询可以响应:

    Declare @customer table
(name varchar(50),custno int,address varchar(50))
Insert into @customer (custno,address)
 values (1, 'Madrid')
Declare @class table
 (custno int,accno int,accbalance int)
Insert into @class (custno,accno)
 values (1,2)
Declare @transaction table
 (accno int,amount int ,address varchar(50))
Insert into @transaction (accno,amount)
 values (2,2)


 select * from @customer

 select * from @class

 select * from @transaction


 Update tr set tr.address = cs.address from @transaction as tr join @class as cl on cl.accno = tr.accno JOIN @customer as cs on cs.custno = cl.custno 


 select * from @transaction

答案 1 :(得分:0)

我建议您直接使用Customer表中原始来源的数据,因此:

Declare @customer table
(   [name] VARCHAR(10),
    custno VARCHAR(10),
    address VARCHAR(10))

Insert into @customer (custno, address)
 values (1, 'Madrid')

Declare @account table
 (  custno INT,
    accno VARCHAR(10),
    accbalance VARCHAR(10))
Insert into @account (custno,accno)
 values (1,2)

Declare @transaction table
 (  accno INT,
    accbalance VARCHAR(10))
Insert into @transaction (accno,accbalance)
 values (2,2);

并且...查询将包括3个表,而不是仅包含事务:

 SELECT T.accno, T.accbalance, C.address 
    FROM @transaction T
    INNER JOIN @account A
        ON A.accno = T.accno
    INNER JOIN @customer C
        ON C.custno = A.custno;

答案 2 :(得分:0)

您可以使用join这样的更新:

UPDATE t
SET t.address = c.address
FROM @transaction t
INNER JOIN @account a
    ON t.accno = a.accno
INNER JOIN @customer c
    ON a.custno = c.custno

答案 3 :(得分:0)

您可以使用join进行尝试。请记住,使用连接进行更新时,您需要将表名称定义为alias,如下所示。

Declare @customer table
(name varchar(20),custno varchar(20),[address] varchar(20))

Insert into @customer (custno,[address])
 values (1, 'Madrid')

Declare @class table
 (custno varchar(20), accno varchar(20), accbalance int)

Insert into @class (custno,accno)
 values (1,2)

Declare @transaction table
 (accno varchar(20), accbalance int, [address] varchar(20))

Insert into @transaction (accno,accbalance)
 values (2,2)

UPDATE t 
SET [address] = c.[address]
FROM @transaction as t
INNER JOIN @class as cl on t.accno = cl.accno
INNER JOIN @customer as c
       ON c.custno = cl.custno

select * from @transaction

输出如下所示。

accno   accbalance  address
---------------------------
2       2           Madrid