简体   繁体   中英

ROWNUM as a pseudo column equivalent in T-SQL?

When using ROWNUM as a pseudo column how would you write the following query using T-SQL? Here is the full query. I realize it's written in PL/SQL and I will need to change addition objects.

BASE AS (
SELECT NULL AS ES_CMPNY_STATUS_KEY
  ,CSG.CMPNY_STATUS_GROUP
  ,CSG.CMPNY_STATUS_GROUP_ID
  ,CSG.CMPNY_STATUS_REASON
  ,CSG.CMPNY_STATUS_REASON_ID
  ,CSF.CMPNY_CURRENT_STATUS_FLAG
  ,TRUNC(SYSDATE) AS LOAD_DATE
  FROM CMPNY_STATUS_GROUP CSG
  CROSS JOIN CMPNY_CURRENT_STATUS_FLAG CSF
  ORDER BY CSG.CMPNY_STATUS_GROUP, CSG.CMPNY_STATUS_REASON

   )SELECT ROWNUM AS ES_CMPNY_STATUS_KEY
   ,CMPNY_STATUS_GROUP
   ,CMPNY_STATUS_GROUP_ID
   ,CMPNY_STATUS_REASON
   ,CMPNY_STATUS_REASON_ID
   ,CMPNY_CURRENT_STATUS_FLAG
   ,LOAD_DATE
 FROM BASE B
UNION
SELECT 0 AS ES_CMPNY_STATUS_KEY
  ,NULL AS CMPNY_STATUS_GROUP
  ,0 AS CMPNY_STATUS_GROUP_ID
  ,NULL AS CMPNY_STATUS_REASON
  ,0 AS CMPNY_STATUS_REASON_ID
  ,0 AS CMPNY_CURRENT_STATUS_FLAG
  ,TRUNC(SYSDATE) AS LOAD_DATE
  FROM DUAL

Use row_number() :

select row_number() over (order by (select null)) as ES_CMPNY_STATUS_KEY

Note that the order by is needed. The (select null) appears -- in practice -- to avoid any additional sorting. In general, though, you would include a column that specifies a sort order for the data you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM