的方式在SQL Server Management Studio中和其他大牌工具,如展鵬做到這一點,是讓一個新的臨時表,在複製的信息,然後刪除舊錶(約束&唯一索引第一),將臨時表重命名爲舊錶名,然後重新添加任何約束和索引。你真的不能重新排序已經存在的東西。
下面是一個例子:
-- here's a sales table
CREATE TABLE [dbo].[Sales](
[SalesId] [int] IDENTITY(1,1) NOT NULL,
[Month] [int] NOT NULL,
[Year] [int] NOT NULL,
[InvoiceAmount] [decimal](15, 2) NOT NULL,
[SalesRepId] [int] NOT NULL,
[BranchId] [int] NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED
(
[SalesId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--Here's the sales table adding a column called description between SalesId & Month
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_Sales
(
SalesId int NOT NULL IDENTITY (1, 1),
Description varchar(MAX) NULL,
Month int NOT NULL,
Year int NOT NULL,
InvoiceAmount decimal(15, 2) NOT NULL,
SalesRepId int NOT NULL,
BranchId int NOT NULL
) ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_Sales ON
GO
IF EXISTS(SELECT * FROM dbo.Sales)
EXEC('INSERT INTO dbo.Tmp_Sales (SalesId, Month, Year, InvoiceAmount, SalesRepId, BranchId)
SELECT SalesId, Month, Year, InvoiceAmount, SalesRepId, BranchId FROM dbo.Sales WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_Sales OFF
GO
DROP TABLE dbo.Sales
GO
EXECUTE sp_rename N'dbo.Tmp_Sales', N'Sales', 'OBJECT'
GO
ALTER TABLE dbo.Sales ADD CONSTRAINT
PK_Sales PRIMARY KEY CLUSTERED
(
SalesId
) WITH(STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
謝謝。這是很多額外的信息。我不認爲我會永遠需要對列重新排序,以至於它可以像我這樣洗牌。 – 2009-08-13 19:23:53
不客氣 - 很高興有所幫助。 – 2009-08-13 19:25:20