我不知道在一个语句而是四个UPDATE语句做它做的伎俩。
最终的选择显示你所拥有的列溢出
DECLARE @CarsSource TABLE (Car VARCHAR(32), CarType1 VARCHAR(32), CarType2 VARCHAR(32), CarType3 VARCHAR(32), CarType4 VARCHAR(32))
DECLARE @CarsDestination TABLE (Car VARCHAR(32), CarType1 VARCHAR(32), CarType2 VARCHAR(32), CarType3 VARCHAR(32), CarType4 VARCHAR(32))
INSERT INTO @CarsSource VALUES ('BMW', 'Fast', 'Well Made', 'Good Handling', NULL)
INSERT INTO @CarsSource VALUES ('Overflow', 'Fast', 'Well Made', 'Good Handling', 'Overflow')
INSERT INTO @CarsDestination VALUES ('BMW', 'Fun Car', NULL, NULL, NULL)
INSERT INTO @CarsDestination VALUES ('Overflow', 'Fun Car', NULL, NULL, NULL)
UPDATE @CarsDestination
SET CarType1 = s.CarType1
, CarType2 = s.CarType2
, CarType3 = s.CarType3
, CarType4 = s.CarType4
FROM @CarsDestination d
INNER JOIN @CarsSource s ON s.Car = d.Car
WHERE d.Cartype1 IS NULL
UPDATE @CarsDestination
SET CarType2 = s.CarType1
, CarType3 = s.CarType2
, CarType4 = s.CarType3
FROM @CarsDestination d
INNER JOIN @CarsSource s ON s.Car = d.Car
WHERE d.Cartype2 IS NULL
UPDATE @CarsDestination
SET CarType3 = s.CarType1
, CarType4 = s.CarType2
FROM @CarsDestination d
INNER JOIN @CarsSource s ON s.Car = d.Car
WHERE d.Cartype3 IS NULL
UPDATE @CarsDestination
SET CarType4 = s.CarType1
FROM @CarsDestination d
INNER JOIN @CarsSource s ON s.Car = d.Car
WHERE d.Cartype4 IS NULL
SELECT *
FROM @CarsSource s
LEFT OUTER JOIN @CarsDestination d ON COALESCE(d.Cartype4, d.Cartype3, d.Cartype2, d.Cartype1) = COALESCE(s.Cartype4, s.Cartype3, s.Cartype2, s.Cartype1)
WHERE d.Car IS NULL
是允许创建中间表和/或临时表吗?这不会发生n一步到位。 – Fosco 2010-10-22 12:54:07
是的,我只需要运行一次。谢谢。 – user53885 2010-10-22 12:59:09
是否有可能在类型列中有一个'洞'?例如'Car:BMW,CarType1:Fun Car,CarType2:NULL,CarType3:Good Handling,CarType4:null' – 2010-10-22 16:12:36