Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate row number without using rownum() in sql server

Tags:

sql-server

I have the following table:

CREATE table prd
(
prdid varchar(10)
)
insert into prd values ('prd1011'),('prd1023'),('prd4532'),('prd2341')

I need to return the same with rownumber without using ROWNUM() built in function. Is that possible?

like image 742
satyajit Avatar asked Mar 23 '26 12:03

satyajit


2 Answers

select *, (
    select count(*)
    from prd p2
    where p1.prdid >= p2.prdid
) as cnt
from prd p1
like image 91
GriGrim Avatar answered Mar 26 '26 10:03

GriGrim


You've failed to specify SQL Server version or motivation for the request.

A SQL Server 2012+ method

SELECT prdid,
       COUNT(*) OVER (ORDER BY prdid ROWS UNBOUNDED PRECEDING)
FROM prd

SQL Fiddle

like image 38
Martin Smith Avatar answered Mar 26 '26 10:03

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!