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

假如想象 提交于 2019-12-24 00:34:46

问题


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


来源:https://stackoverflow.com/questions/4252394/in-t-sql-how-to-reference-to-table-variable-in-the-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!