In T-SQL, how to reference to table variable in the subquery?
Asked Answered
R

1

2

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
Roadside answered 23/11, 2010 at 3:6 Comment(0)
S
5

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
Satinet answered 23/11, 2010 at 3:18 Comment(1)
The point is, we have to declare the alias of the table variable inside the subqueryRoadside

© 2022 - 2024 — McMap. All rights reserved.