如何使用一个更新语句将以下子查询转换为联接

时间:2013-04-09 07:15:35

标签: sql-server tsql

以下是我的完整查询,最终目的是更新索赔表。但它应该只有一个语句没有任何子查询,只允许连接,因为我将在一个不支持子查询的设备中运行它:

DECLARE @DecWdrwn as TABLE(CtryId smallint, CmId int, DecWdrwnDt int);
WITH s AS 
(
    SELECT  
        Ctryid,CmId,Dt,
        ISNULL((
            SELECT  max(CmHistDtTmId) 
            FROM    ClaimHistory l 
            WHERE   St = 3 
                    AND l.Ctryid = c.Ctryid 
                    AND l.CmId = c.CmId)
            , 0) MaxDec, 
        ISNULL((
            SELECT  max(CmHistDtTmId) 
            FROM    ClaimHistory l 
            WHERE   St = 7 
                    AND l.Ctryid = c.Ctryid 
                    AND l.CmId = c.CmId)
            , 0) MaxSet
    FROM 
        ClaimHistory c
    WHERE 
        St =3
)

INSERT  INTO @DecWdrwn
SELECT  CtryId, CmId, Max(Dt) DecDt 
FROM    s
WHERE   MaxSet > MaxDec
GROUP   BY CtryId,CmId

非常感谢您的回复......

UPDATE  Claims 
SET     CmDclnWdwnDt = (
            SELECT  DecWdrwnDt 
            FROM    @DecWdrwn d 
            WHERE   d.CmId = Claims.CmId 
                    AND d.CtryId = Claims.CtryId
            )
WHERE   EXISTS (
        SELECT  * 
        FROM    @DecWdrwn d 
        WHERE   d.CmId = Claims.CmId 
                AND d.CtryId = Claims.CtryId
        )

1 个答案:

答案 0 :(得分:1)

请尝试INNER JOIN Update

UPDATE a
SET a.CmDclnWdwnDt = b.DecWdrwnDt
FROM Claims a, @DecWdrwn b
WHERE a.CmId = b.CmId AND
        a.CtryId =b.CtryId