CTE更新

时间:2014-11-04 18:04:05

标签: sql sql-server

这是一个使用CTE的简单查询,但行为不符合我的想法。

想法是用precio_90 = null过滤那些记录,然后用mytable2的价格更新字段precio_90,其中codigo = codigo在特定日期。 目前,我在没有实际过滤器的情况下更新了所有记录。

DECLARE @mytable1 TABLE
(
codigo VARCHAR(10) NOT NULL,
precio_90 NUMERIC(10, 4) 
);

DECLARE @mytable2 TABLE
(codigo VARCHAR(10) NOT NULL,
fecha date NOT NULL,
precio NUMERIC(10, 4) NOT NULL
);

INSERT INTO @mytable1(codigo, precio_90)
VALUES ('stock1', 51),
('stock1', 3),
('stock1',5),
('stock1',6),
('stock1',2),
('stock1',7),
('stock1',null)

INSERT INTO @mytable2(codigo, fecha, precio)
VALUES ('stock1', '20140710', 26),
('stock2', '20140711', 66),
('stock1', '20140712', 23),
('stock2', '20140710', 35);

;WITH CTE_1
as
( SELECT  codigo, precio_90           
  FROM  @mytable1 
  where precio_90 is null )

UPDATE t1 
SET t1.precio_90= t2.[precio]
from @mytable1 as t1
INNER JOIN @mytable2 as t2
ON t1.codigo = t2.[codigo] and '2014-07-10'=t2.fecha

3 个答案:

答案 0 :(得分:1)

从您的样本@mytable1插入,所有使用codigo ='stock1'插入的记录。因此,在UPDATE语句中,您将@ mytable1中的所有记录从@ mytable2更新为stock1级。

例如,如果您的样本表1中包含stock2的记录,请执行以下操作:

INSERT INTO @mytable1(codigo, precio_90)
VALUES ('stock1', 51),
('stock1', 3),
('stock1',5),
('stock1',6),
('stock2',2), -- Set to stock2
('stock2',7), -- Set to stock2
('stock1',null)

然后您的CTE正在更新7/10/2014记录中指定的stock2记录:

codigo     precio_90
---------- ---------------------------------------
stock1     26.0000
stock1     26.0000
stock1     26.0000
stock1     26.0000
stock2     35.0000
stock2     35.0000
stock1     26.0000

答案 1 :(得分:1)

   UPDATE t1 
          SET t1.precio_90 = t2.[precio]
     from @mytable1 as t1
     JOIN @mytable2 as t2
       ON t1.[codigo] = t2.[codigo] 
      and t2.fecha = '2014-07-10' 
      and t1.precio_90 is null 
      and t2.precio_90 is null 

答案 2 :(得分:1)

首先,您不能在更新中的任何位置使用CTE,这就是为什么您的结果没有正确过滤的原因。其次,您不需要CTE ...您可以在更新中过滤precio_90 is null

UPDATE t1 
SET t1.precio_90= t2.[precio]
from @mytable1 as t1
INNER JOIN @mytable2 as t2 ON t1.codigo = t2.codigo
where t1.precio_90 is null
    and '2014-07-10'=t2.fecha