临时表更新

时间:2013-02-27 17:50:40

标签: sql sql-server tsql sql-update temp-tables

查询:

SELECT ID, T.c.value('@Address', 'nvarchar(20)' ) as Address
INTO #TMP
FROM TABLE1
    CROSS APPLY XMLData.nodes('/Document') AS T(c)

UPDATE TABLE1
SET HomeAddress = (SELECT TOP 1 t.Address
                   FROM #TMP t
                   WHERE t.ID = ID)

主要是,我需要将数据OUT从XML字段复制到同一个表中的普通字段。

问题:

  1. 所有记录在Table1上获取HomeAddress的原因是什么?
  2. 真的Cursor是更新Table1上值的唯一方法吗?

3 个答案:

答案 0 :(得分:22)

UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on T1.ID = t2.HomeAddressID
and t2.HomeAddress <> t1.address

使用联接。无需临时表或相关子查询。

如果表1处于一对多的关系中,这些是处理它的一些可能性。如果你有一个值表示一个且只有一个记录(我们的系统中有一个字段可以选择最重要的地址,但是它有一个触发器来保证唯一性),试试这个:

UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on t1.ID = t2.HomeAddressID
WHERE t1.somefield = 'somevalue'
and t2.HomeAddress <> t1.address

如果您需要在asome其他字段(例如最近的日期)上创建唯一记录,请尝试以下变体:

UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on t1.ID = t2.HomeAddressID
join (select id, max(somedatefield) from  table1 group by id) t3 on t3.id = t1.id
Where  t2.HomeAddress <> t1.address

答案 1 :(得分:2)

在更新时,我需要对表格进行全面合格,如下所示:

更新表1 SET TABLE1.HomeAddress =(SELECT TOP 1 t.Address
                   来自#TMP t
                   WHERE.TIT = TABLE1.ID)

答案 2 :(得分:0)

SELECT P.TipoComprob,P.NoComprob,C.Importe as ImpIVA1,ROUND(100/P.ImpGravado*C.Importe,1)
 as PorcIVA1 
       INTO #Temporal
       FROM ComprobProv AS P
       LEFT JOIN PasesCompras AS C ON C.TipoComprob=P.TipoAsiento AND 
C.NoComprob=P.NoComprob
WHERE P.PorcIVA1 =0 and P.CatIVA = 'Ri' AND P.ImpGravado>0 AND C.CodCuenta=110303010 AND ROUND(100/P.ImpGravado*C.Importe,1) IN (21.00,10.50,27.00);
go

select * from #Temporal;
go

UPDATE 
   t1 
SET 
   t1.ImpIVA1 =  t2.ImpIVA1, t1.PorcIVA1 = t2.PorcIVA1
FROM
   dbo.ComprobProv t1
   INNER JOIN #Temporal t2
   ON t1.TipoComprob = t2.TipoComprob AND t1.NoComprob = t2.NoComprob;
go

-请注意,“ GO”对于保留SQL Server 2017中的上下文很重要,否则您会发现 “未知字段名称”错误。