简体   繁体   中英

How can I add a column and populate it with a number after sorting a table?

I have this table:

CREATE TABLE [dbo].[Phrase]
(
    [PhraseId] [uniqueidentifier] NOT NULL,
    [PhraseNum] [int] NULL
    [English] [nvarchar](250) NOT NULL,

    PRIMARY KEY CLUSTERED ([PhraseId] ASC)
) ON [PRIMARY]
GO

What I would like to do is to sort the table and populate the column PhraseNum with a number where the first row of the sorted table is 1 and each row after that has a value one larger than the one before.

In SQL Server, you would do this with an identity column:

CREATE TABLE [dbo].[Phrase](
    [PhraseId] [uniqueidentifier] NOT NULL PRIMARY KEY,
    [PhraseNum] int identity(1, 1) NOT NULL
    [English] [nvarchar](250) NOT NULL
);

Having a unique identify as a (clustered) primary key is a really, really bad idea. Why? New values are not ordered. That means that the data has to be re-ordered for each insert -- causing fragmentation.

You should use the PhraseNum column as the primary key.

Alan, if data in PhraseNum is not important (as I could see in your post), you can drop that column and add as an identity column

ALTER TABLE Phrase drop column PhraseNum ;
ALTER TABLE Phrase Add PhraseNum int identity(1,1) not null;

The numbering of PhraseNum will be done by the cluster index sorting criteria, so by PhraseId

But it is safe to test on a test database first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM