更新表中的多个记录从另一个SQL 2008获取值

时间:2013-08-31 12:30:00

标签: sql sql-server sql-server-2008 tsql

我正在尝试更新表列并从另一个列中设置值 像这样

UPDATE dbo.TempTable t2
SET    Introd = t1.Introd, AgtCode = t1.[Agt Code], PIN = t1.PIN, IDNo = t1.[ID No] 
FROM   dbo.CustomerData t1
WHERE  t2.PolicyNo = t1.Policy
AND    t2.Prod = t1.Prod
AND    t2.Introd IS DISTINCT FROM t1.Introd

但它不能与我合作,

3 个答案:

答案 0 :(得分:1)

UPDATE
    Table_1
SET
    Table_1.FieldToBeUpdated = T2.FieldFromWhichToBeUpdated
FROM
    Table_1 T1
INNER JOIN
    Table_2 T2
ON 
    T1.ConditionFieldFromTable1 = T2.ConditionFieldFromTable2

可选地

UPDATE
    Table_1 T1,Table_2 T2
SET
    T1.FieldToBeUpdated = T2.FieldFromWhichToBeUpdated
WHERE
    SI.AnyField = RAN.AnyOtherField

答案 1 :(得分:1)

您似乎更多地使用Postgres格式的SQL。这是SQL Server的等价物:

UPDATE t2
    SET    Introd = t1.Introd,
           AgtCode = t1.[Agt Code],
           PIN = t1.PIN,
           IDNo = t1.[ID No] 
    FROM   dbo.TempTable t2 join
           dbo.CustomerData t1
           on t2.PolicyNo = t1.Policy and
              t2.Prod = t1.Prod and
              (t2.Introd <> t1.Introd or
               t2.Introd is NULL and t1.Introd is not NULL or
               t2.Introd is not NULL and t1.Introd is NULL
              )

答案 2 :(得分:0)

第一种方法:

    UPDATE dbo.TempTable t2
    SET    t2.Introd = t1.Introd, t2.AgtCode = t1.[Agt Code], 
           t2.PIN = t1.PIN, t2.IDNo = t1.[ID No] 
    FROM t2
    LEFT JOIN dbo.CustomerData t1
    ON t2.PolicyNo = t1.Policy
    AND t2.Prod = t1.Prod
    AND t2.Introd IS DISTINCT FROM t1.Introd

第二种方法:

UPDATE dbo.TempTable t2
SET    t2.Introd = t1.Introd, t2.AgtCode = t1.[Agt Code], 
t2.PIN = t1.PIN, t2.IDNo = t1.[ID No]
FROM t2, dbo.CustomerData t1
where t2.PolicyNo = t1.Policy
AND t2.Prod = t1.Prod
AND t2.Introd IS DISTINCT FROM t1.Introd