Equivalent of Oracle's RowID in SQL Server

前端 未结 13 1208
长发绾君心
长发绾君心 2020-11-27 04:22

What\'s the equivalent of Oracle\'s RowID in SQL Server?

13条回答
  •  执念已碎
    2020-11-27 05:22

    From http://vyaskn.tripod.com/programming_faq.htm#q17:

    Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or how to generate output with row number in SQL Server?

    There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational database, rows within a table are not ordered and a row id won't really make sense. But if you need that functionality, consider the following three alternatives:

    • Add an IDENTITY column to your table.

    • Use the following query to generate a row number for each row. The following query generates a row number for each row in the authors table of pubs database. For this query to work, the table must have a unique key.

      SELECT (SELECT COUNT(i.au_id) 
              FROM pubs..authors i 
              WHERE i.au_id >= o.au_id ) AS RowID, 
             au_fname + ' ' + au_lname AS 'Author name'
      FROM          pubs..authors o
      ORDER BY      RowID
      
    • Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the IDENTITY() function. Creating a temporary table will be costly, especially when you are working with large tables. Go for this approach, if you don't have a unique key in your table.

提交回复
热议问题