-1

如果我在这里创建一个表变量:

declare @Table Table (ProductID int, Color = varchar(60))

然后当然填充它,并尝试在下面的UpdatewithJoin语句中使用它,我得到错误。

UPDATE [Product]
    SET [Product].[Active] = 1                      
    ,[Product].[Color] = t.[Color]
    INNER JOIN @Table t 
    ON t.[ProductID] = [Product].[ProductID]

错误:

 Msg 156, Level 15, State 1, Procedure
 Incorrect syntax near the keyword 'INNER'.

任何建议如何做到这一点?

4

1 回答 1

3

您也可以这样做(适用于 SQL Server 和所有符合 ANSI SQL 的数据库):

UPDATE [Product] SET 
    [Product].[Active] = 1                      
    ,[Product].[Color] = t.[Color]
FROM @Table t 
WHERE t.[ProductID] = [Product].[ProductID]

SQL Server 的专有 UPDATE FROM 有一些需要改进的地方,您可以轻松地更改UPDATE语句以使其匹配整个表,无论是否没有匹配的行。

很容易塑造这个仅匹配行的更新...... http://www.sqlfiddle.com/#!3/8b5a3/26

update p SET
  Qty = t.Qty
from Product p
inner join Latest t 
on t.ProductId = p.ProductId;

...要UPDATE匹配所有行,您只需将其更改INNER JOINLEFT JOINhttp ://www.sqlfiddle.com/#!3/8b5a3/27

update p SET
  Qty = ISNULL(t.Qty,0)
from Product p
left join Latest t 
on t.ProductId = p.ProductId;


select * from Product;

而如果你想UPDATE匹配的行来塑造 ANSI SQL ... http://www.sqlfiddle.com/#!3/8b5a3/28

update Product SET
  Qty = t.Qty
from Latest t
where t.ProductId = Product.ProductId

...要UPDATE匹配所有行的语句,您必须稍微调整查询:http ://www.sqlfiddle.com/#!3/8b5a3/29

update Product SET
  Qty = ISNULL(t.Qty, 0)
from 
(
  select x.ProductId, lat.Qty
  from Product x
  left join Latest lat on lat.ProductId = x.ProductId
) as t  
where t.ProductId = Product.ProductId;

尽管作为开发中的大多数选择,人们应该权衡代码可读性/可维护性与灵活性方面的利弊

数据样本:

create table Product
(
  ProductId int primary key not null,
  Name varchar(50) not null,
  Qty int not null
  );


insert into Product(Name,Qty) values
(1,'CAR',1),
(2,'Computer',1000),
(3,'Shoes',2);


create table Latest
(
  ProductId int primary key not null,
  Qty int not null
);

insert into Latest(ProductId, Qty) values
(2,2000),
(3,3);
于 2012-04-26T03:18:16.460 回答