从表变量使用Update Join语句时出错

时间:2012-04-26 03:14:28

标签: sql sql-server sql-server-2005

如果我在这里制作一个表变量:

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

然后填充它,当然尝试在Update Join语句中使用它,如下所示,我收到错误。

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'.

有任何建议怎么做?

1 个答案:

答案 0 :(得分: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 JOIN更改为LEFT 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;

然而,如果你想用仅匹配行来制作ANSI SQL UPDATE ...... 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);