简体   繁体   English

在对表格进行排序后,如何添加列并用数字填充?

[英]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. 我想做的是对表进行排序,并用一个数字填充列PhraseNum ,其中已排序表的第一行为1 ,此后的每一行的值都比之前的大一个。

In SQL Server, you would do this with an identity column: 在SQL Server中,您可以使用一个标识列来做到这一点:

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. 这意味着必须为每个insert重新排序数据-导致碎片。

You should use the PhraseNum column as the primary key. 您应该将PhraseNum列用作主键。

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 艾伦(Alan),如果PhraseNum中的数据并不重要(如您在帖子中所见),则可以删除该列并添加为标识列

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 PhraseNum的编号将由聚簇索引排序标准完成,因此由PhraseId进行

But it is safe to test on a test database first 但是先在测试数据库上进行测试是安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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