为Microsoft sql server视图中的每一行分配ID

可以说我有这样一张桌子:

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

)
和几行数据如:

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');

我想创建一个为每行分配ID的视图,
我使用了下面的select语句:

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

结果是完全可以接受的,但是当我尝试创建视图时问题出现了

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

我的问题是:

1-如何从上面提到的select语句创建视图?

2-我有什么替代方法可以使用吗?

最佳答案 除非您使用top,否则视图中不允许使用order by.根据
documentation

The SELECT clauses in a view definition cannot include the following:

  • An ORDER BY clause, unless there is also a TOP clause in the select list of the SELECT statement

因此,如果没有订单,您的声明就可以了:

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

即使您在顶部包含订单,也无法按特定顺序保证结果.您只能通过外部查询使用订单来保证.

点赞