如何更新内部联接结果?

时间:2016-01-18 12:16:33

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

我有两张桌子:

  1. 地址(有1000多行)
  2. GoverningBody,(仅有7个)
  3. dbo.GoverningBody使用dbo.Address.AddressID链接(唯一ID)

    我想更新所有address1列(来自dbo.Address) 我的内部联接dbo.address.addressID =dbo.governingbody.addressID

    SELECT 
        GB.GoverningBodyName,
        Ad.Address1,
        Ad.AddressID,
        GB.GoverningBodyID
    FROM
        Address Ad
    INNER JOIN 
        (SELECT 
             GoverningBodyID,
             AddressID,
             GoverningBodyName
         FROM   
             GoverningBody) GB ON ad.AddressID = gb.AddressID 
    

    我想将Address1值更新为:

    'Test1','Test2','Test3' etc...
    

    希望这是有道理的。

    谢谢,

    萨姆

2 个答案:

答案 0 :(得分:0)

SELECT SUM(UNCOLLECTED)
FROM LIQUIDATIONSDETAILS LD JOIN
     ??? L       -- I don't know what table "L" refers to
     ON LD.COMPANYID = L.COMPANYID AND
        LD.GROUPID = L.GROUPID AND
        LD.PERIODID = L.PERIODID 
WHERE LD.FORMTYPE IN (1, 2, 3) OR
      (LD.FORMTYPE = 4 AND L.PERIODID > '2013-2014')

答案 1 :(得分:0)

SQL Server 2008具有ROW_NUMBER功能。

我将您的查询包装到CTE(公用表表达式)中,并带有行号的额外列并更新CTE。您可以使用ORDER BY函数中的ROW_NUMBER来确定如何将数字分配给行。

顺便说一句,您的INNER JOIN并不真正需要子查询,它可以用更简单的形式编写。优化器足够智能,只能读取所需的列。事实上,在UPDATE查询中,您不需要GoverningBodyNameGoverningBodyID列,而且很可能是优化者不会阅读它们。

WITH
CTE
AS
(
    SELECT 
        GB.GoverningBodyName,
        Ad.Address1,
        Ad.AddressID,
        GB.GoverningBodyID,
        ROW_NUMBER() OVER (ORDER BY Ad.AddressID) AS rn
    FROM
        Address AS Ad
        INNER JOIN GoverningBody AS GB ON ad.AddressID = gb.AddressID
)
UPDATE CTE
SET Address1 = 'Test' + CAST(rn as varchar(10))
;