In T-SQL, how to reference to table variable in th

2019-07-19 02:10发布

问题:

I've declared a table variable '@t', and have correctly performed the 'INSERT-INTO-SELECT'. When I was trying to query the table variable with some additional computation for per-group row numbering, I got error either "Must declare the variable" when using '@t' directly or "invalid object name" while using alias of '@t'. Please kindly advise.

SELECT 
    *,
    (SELECT COUNT(*) FROM "LTV" "COUNTER"
     WHERE 
        "COUNTER"."Collateral_ID" = "LTV"."Collateral_ID"
        AND
        "COUNTER"."m_il_no" = "LTV"."m_il_no"
        AND
        "COUNTER"."Ref_Key" <= "LTV"."Ref_Key"
     GROUP BY "COUNTER"."Collateral_ID", "COUNTER"."m_il_no"
    ) "MIL_IDX"

FROM @t AS LTV

回答1:

Use:

SELECT x.*,
       y.num
  FROM @t x
  JOIN (SELECT t.collateral_id,
               t.m_il_no,
               COUNT(*) AS num
          FROM @t t
      GROUP BY t.collateral_id, t.m_il_no) y ON y.collateral_id = x.collateral_id
                                            AND y.m_il_no = x.m_il_no