1.新建一數據表,里面有字段id,將id設為為主鍵
create table tb(id int,constraint pkid primary key (id))
create table tb(id int primary key )
2.新建一數據表,里面有字段id,將id設為主鍵且自動編號
create table tb(id int identity(1,1),constraint pkid primary key (id))
create table tb(id int identity(1,1) primary key )
3.已經建好一數據表,里面有字段id,將id設為主鍵
alter table tb alter column id int not null
alter table tb add constraint pkid primary key (id)
4.刪除主鍵
Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('tb') and xtype='PK';
if @Pk is not null
exec('Alter table tb Drop '+ @Pk)
create table tb(id int,constraint pkid primary key (id))
create table tb(id int primary key )
2.新建一數據表,里面有字段id,將id設為主鍵且自動編號
create table tb(id int identity(1,1),constraint pkid primary key (id))
create table tb(id int identity(1,1) primary key )
3.已經建好一數據表,里面有字段id,將id設為主鍵
alter table tb alter column id int not null
alter table tb add constraint pkid primary key (id)
4.刪除主鍵
Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('tb') and xtype='PK';
if @Pk is not null
exec('Alter table tb Drop '+ @Pk)
另外方法:
create table ttt
(
t1 int,
t2 varchar(8)
)
現在想把字段t1設為自增字段和主鍵.
那麼運行下面的代碼:
CREATE TABLE dbo.Tmp_ttt
(
t1 int NOT NULL IDENTITY (1, 1),
t2 varchar(8) NULL
)
go
SET IDENTITY_INSERT dbo.Tmp_ttt ON
go
IF EXISTS(SELECT * FROM dbo.ttt)
EXEC('INSERT INTO dbo.Tmp_ttt (t1, t2)
SELECT t1, t2 FROM dbo.ttt TABLOCKX')
go
SET IDENTITY_INSERT dbo.Tmp_ttt OFF
go
DROP TABLE dbo.ttt
go
EXECUTE sp_rename N'dbo.Tmp_ttt', N'ttt', 'OBJECT'
go
ALTER TABLE dbo.ttt ADD CONSTRAINT
PK_ttt PRIMARY KEY CLUSTERED
(
t1
) ON [PRIMARY]
COMMIT
為什麼不用
alter table ttt drop column t1
go
alter table ttt add t1 identity(1,1) not null
go
alter table ttt add constrain primary key pk_t (t1)
的方法.
是因為先刪掉一列.再增加一列.
那麼列的順序就改變了.
有可能帶來意想不到的問題.
(比方說,你的程序中有個insert語句是沒有寫字段名的)
(
t1 int,
t2 varchar(8)
)
現在想把字段t1設為自增字段和主鍵.
那麼運行下面的代碼:
CREATE TABLE dbo.Tmp_ttt
(
t1 int NOT NULL IDENTITY (1, 1),
t2 varchar(8) NULL
)
go
SET IDENTITY_INSERT dbo.Tmp_ttt ON
go
IF EXISTS(SELECT * FROM dbo.ttt)
EXEC('INSERT INTO dbo.Tmp_ttt (t1, t2)
SELECT t1, t2 FROM dbo.ttt TABLOCKX')
go
SET IDENTITY_INSERT dbo.Tmp_ttt OFF
go
DROP TABLE dbo.ttt
go
EXECUTE sp_rename N'dbo.Tmp_ttt', N'ttt', 'OBJECT'
go
ALTER TABLE dbo.ttt ADD CONSTRAINT
PK_ttt PRIMARY KEY CLUSTERED
(
t1
) ON [PRIMARY]
COMMIT
為什麼不用
alter table ttt drop column t1
go
alter table ttt add t1 identity(1,1) not null
go
alter table ttt add constrain primary key pk_t (t1)
的方法.
是因為先刪掉一列.再增加一列.
那麼列的順序就改變了.
有可能帶來意想不到的問題.
(比方說,你的程序中有個insert語句是沒有寫字段名的)