具有内部联接的SQL更新查询语法

时间:2010-10-05 19:49:35

标签: sql sql-server tsql sql-server-2000 sql-update

有人能在此查询中找到我的错误吗?我正在使用SQL Server 2000,我想将CostEntry表中的所有条目更新为ActiveCostDetails表中的相应值。 where子句可以使用select语句。

    UPDATE CostEntry CE 
INNER JOIN ActiveCostDetails As AD ON CostEntry.lUniqueID = ActiveCostDetails.UniqueID
       SET CostEntry.sJobNumber = ActiveCostDetails.JobNumber
     WHERE CostEntry.SEmployeeCode = '002'
       AND SubString(CostCentre, 1, 1) = sDepartmentCode
       AND substring(CostCentre, 3, 1) = sCategoryCode
       AND substring(CostCentre, 5, 2) = sOperationCode

3 个答案:

答案 0 :(得分:52)

SET需要在查询的FROM\JOIN\WHERE部分之前。

UPDATE CE
SET sJobNumber = AD.JobNumber
FROM CostEntry CE 
    INNER JOIN ActiveCostDetails As AD 
        ON CE.lUniqueID = AD.UniqueID
WHERE CE.SEmployeeCode = '002'
    AND SubString(CostCentre, 1, 1) = sDepartmentCode
    AND substring(CostCentre, 3, 1) = sCategoryCode
    AND substring(CostCentre, 5, 2) = sOperationCode

答案 1 :(得分:2)

一旦为表设置了别名,就不能使用表名。以这种方式尝试查询,它将起作用。

UPDATE CostEntry CE 

        INNER JOIN 
            ActiveCostDetails AD 
            ON (CE.lUniqueID = AD.UniqueID)

           SET CE.sJobNumber = AD.JobNumber

         WHERE CE.SEmployeeCode = '002'
           AND SubString(CostCentre, 1, 1) = sDepartmentCode
           AND substring(CostCentre, 3, 1) = sCategoryCode
           AND substring(CostCentre, 5, 2) = sOperationCode

答案 2 :(得分:1)

这应该有效

UPDATE CE
SET CostEntry.sJobNumber = ActiveCostDetails.JobNumber
FROM CostEntry CE 
INNER JOIN ActiveCostDetails As AD ON CostEntry.lUniqueID = ActiveCostDetails.UniqueID       
     WHERE CostEntry.SEmployeeCode = '002'
       AND SubString(CostCentre, 1, 1) = sDepartmentCode
       AND substring(CostCentre, 3, 1) = sCategoryCode
       AND substring(CostCentre, 5, 2) = sOperationCode