2008-09-26 91 views

回答

10

如果你正在利用的GUID這應該是好的,容易,如果你正在尋找一個整數ID,你將不得不等待另一個答案。

SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1 

的NEWID()會生成一個新的GUID爲你,你可以爲你自動生成的ID列中使用。

+0

簡而不遜我所需。 – 2016-11-14 14:24:43

1

這可能是你在找什麼?

選擇NEWID()*從表

13

IDENTITY(INT,1,1)應該這樣做,如果你正在做一個選擇進入。在SQL 2000中,我只是將結果放在臨時表中,然後查詢這些後綴。

+0

謝謝!這正是我正在尋找的。 (你有一個錯字,應該是「IDENTITY(int,1,1)」。) – 2011-04-26 21:52:49

1

你想要一個遞增的整數列與您的記錄集返回?如果是這樣的: -

--Check for existance 
if exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1) 
drop table dbo.t 
go 

--create dummy table and insert data 
create table dbo.t(x char(1) not null primary key, y char(1) not null) 
go 
set nocount on 
insert dbo.t (x,y) values ('A','B') 
insert dbo.t (x,y) values ('C','D') 
insert dbo.t (x,y) values ('E','F') 

--create temp table to add an identity column 
create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null) 

--populate the temporary table 
insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t 

--return the data 
select i,x,y from dbo.#TempWithIdentity 

--clean up 
drop table dbo.#TempWithIdentity 
0

您可以直接在SQL2000爲此,按照微軟的網頁:http://support.microsoft.com/default.aspx?scid=kb;en-us;186133

select rank=count(*), a1.au_lname, a1.au_fname 
    from authors a1, authors a2 
    where a1.au_lname + a1.au_fname >= a2.au_lname + a2.au_fname 
    group by a1.au_lname, a1.au_fname 
    order by rank 

用這種方法唯一的問題是,(傑夫上的SQL Server中央說)這是三角形連接。所以,如果你有十條記錄,這將是快速的,如果你有一千條記錄它會很慢,並有一百萬條記錄它可能永遠不會完成!

在這裏看到三角形的一個更好的解釋聯接:http://www.sqlservercentral.com/articles/T-SQL/61539/


0
Select (Select count(y.au_lname) from dbo.authors y 
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid, 
x.au_lname,x.au_fname from authors x group by au_lname,au_fname 
order by Counterid --Alternatively that can be done which is equivalent as above.. 
11

這將在SQL Server 2008工作

select top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp 

乾杯

+1

問題是關於`sql2000` – 2012-10-26 17:06:53

6

這裏有一個簡單的方法它們排列在排序之後,然而它們被排序,即插入到你的表中。在您的SELECT語句中,只需添加字段

ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.