不知道为什么总是说对于nvarchar运算符divide无效
——答案是:我定义的字段太短了!!!!
-
创建表的时候同时建立默认值约束
默认值就是一种约束。查约束就能看见。刷新一下,在设计里也能看见。
CREATE TABLE 表 ( 字段名称 varchar(4) default('设定的默认值')) -
在已存在的表中建立默认值约束
alter table Image201803
add default ('/') for SerialNumber with values
ALTER TABLE [dbo].[Image201712] ADD CONSTRAINT [DF_Image201712_SerialNumber] DEFAULT ('/') FOR [SerialNumber]
GO
ALTER TABLE [dbo].[Image201803] ADD DEFAULT ('/') FOR [SerialNumber]
3.1.新建一数据表,里面有字段id,将id设为为主键
create table tb(id int,constraint pkid primary key (id))
create table tb(id int primary key )
3.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.3.已经建好一数据表,里面有字段id,将id设为主键
alter table tb alter column id int not null
alter table tb add constraint pkid primary key (id)
3.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語句是沒有寫字段名的)
网友评论