Assign identifier to each row in SQL server view

Let's say I have a table like this:

create table MyTable (
 Myname varchar (10) primary key not null

) and several lines of data, for example:

insert into MyTable values ('john');
insert into MyTable values ('Brad');
insert into MyTable values ('James');
insert into MyTable values ('Anna');
insert into MyTable values ('Eric');
insert into MyTable values ('Hossein');

I want to create a view that assigns an identifier to each row, I used the select statement below:

   select rank() OVER (ORDER BY Myname) as ID, MyTable.Myname 
   from MyTable 
   order by ID 

The results are acceptable, but the problem occurs when I try to create a view

create view myview as 
 select rank() OVER (ORDER BY Myname) as ID, MyTable.Myname 
   from MyTable 
   order by ID 

My questions:

1- how can I create a view from the select statement above?

2 Is there an alternative way that I can use?

+4
source share
1 answer

order bynot allowed in view if you are not using top. According to the documentation :

SELECT :

  • ORDER BY, TOP SELECT

, order by:

create view myview as 
   select rank() OVER (ORDER BY Myname) as ID, MyTable.Myname 
   from MyTable ;

order by top, . , order by .

+2

All Articles