将SELECT转换为UPDATE查询

时间:2017-08-02 17:20:24

标签: sql sql-server

我正在尝试将此SELECT查询转换为UPDATE查询...

SELECT 
    ID, BL.[Tipo_Actividad], ACC.Tipo_Actividad AS TipoActividad,
    [Aplicacion], AP.Descripcion AS AplicacionN,
    [Gestor_APP], TIBM.Contacto AS Nombre, [Gestor_APP_Sust],
    TIBM1.Contacto AS NombreSAP, [Hostname_APP], [IP_APP],
    [Gestor_BD], TIBM2.Contacto AS NombreGBD, [Gestor_BD_Sust],
    TIBM3.Contacto NombreGSBD, [Hostname_BD], [IP_BD],
    [Sitios_Afectados], [Subsitios], [horarios], [dias], [No_Programar], [F20]  
FROM 
    [ADOGESCAM].[dbo].[Baseline] BL 
INNER JOIN 
    ACTIVIDADES_CAMBIO ACC ON BL.[Tipo_Actividad] = ACC.Id_Actividad 
INNER JOIN 
    APLICACIONESINVO_CAMBIO AP ON BL.[Aplicacion] = AP.id_ApCambio 
INNER JOIN 
    Torres_IBM TIBM ON BL.[Gestor_APP] = TIBM.Cve_TorresIBM 
INNER JOIN 
    Torres_IBM TIBM1 ON BL.[Gestor_APP_Sust] = TIBM1.Cve_TorresIBM 
INNER JOIN 
    Torres_IBM TIBM2 ON BL.[Gestor_BD] = TIBM2.Cve_TorresIBM 
INNER JOIN 
    Torres_IBM TIBM3 ON BL.[Gestor_BD_Sust] = TIBM3.Cve_TorresIBM;

1 个答案:

答案 0 :(得分:1)

  

更新该查询生成的数据

例如,我们需要更新[ADOGESCAM].[dbo].[Baseline]中的内容:

UPDATE BL 
SET SomeColumn = AnotherColumn
    --,here comes another columns from [ADOGESCAM].[dbo].[Baseline]
FROM [ADOGESCAM].[dbo].[Baseline] BL 
inner join ACTIVIDADES_CAMBIO ACC on BL.[Tipo_Actividad] = ACC.Id_Actividad 
inner join APLICACIONESINVO_CAMBIO AP on BL.[Aplicacion] = AP.id_ApCambio 
inner join Torres_IBM TIBM on BL.[Gestor_APP] = TIBM.Cve_TorresIBM 
inner join Torres_IBM TIBM1 on BL.[Gestor_APP_Sust] = TIBM1.Cve_TorresIBM 
inner join Torres_IBM TIBM2 on BL.[Gestor_BD] = TIBM2.Cve_TorresIBM 
inner join Torres_IBM TIBM3 on BL.[Gestor_BD_Sust] = TIBM3.Cve_TorresIBM;
  

使用SELECT查询的结果更新表77777中的数据

我猜你需要MERGE SQL Server(从2008年开始):

;WITH cte AS (
--your query here
)

MERGE 77777 as t
USING cte as s
ON t.UniqueIDcolumn = s.UniqueIDcolumn --maybe more columns here,
--There must be 1 row in target (t) table that is corresponding to 1 row in source (s) table
WHEN MATCHED THEN 
    UPDATE SET Column1 = s.Column1 
           --, etc
WHEN NOT MATCHED THEN INSERT 
    INSERT (Column1, Column2, ...etc)  
    VALUES (s.Column1, s.Column2, ...etc);

这将更新已存在的内容并插入新数据。