sql的一些基本操作(创建表、删除表、增加字段)

新建表:
create table [表名]
(
[自动编号字段] int IDENTITY (1,1) PRIMARY KEY ,
[字段1] nVarChar(50) default '默认值' null ,
[字段2] ntext null ,
[字段3] datetime,
[字段4] money null ,
[字段5] int default 0,
[字段6] Decimal (12,4) default 0,
[字段7] image null ,
)

例:CREATE TABLE [dbo].[ZYBL_BASYZTB](
[JZLSH] varchar NOT NULL,
[YLJGDM] varchar NOT NULL,
[RYSJ] [datetime] NULL,
[YNZJ] [numeric](18, 3) NULL,
[PFKL] [numeric](18, 3) NULL,
[QTHCF] [numeric](18, 3) NULL,
[GZHCF] [numeric](18, 3) NULL,
[PTHCF] [numeric](18, 3) NULL,
[WSCLF] [numeric](18, 3) NULL,
CONSTRAINT [PK__ZYBL_BAS__0F91D671C8DCF39F] PRIMARY KEY CLUSTERED
(
[PCH] ASC,
[JZLSH] ASC,
[YLJGDM] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

删除表:
Drop table [表名]

插入数据:
INSERT INTO [表名] (字段1,字段2) VALUES (100,'51WINDOWS.NET')

删除数据:
DELETE FROM [表名] WHERE [字段名]>100

更新数据:
UPDATE [表名] SET [字段1] = 200,[字段2] = '51WINDOWS.NET' WHERE [字段三] = 'HAIWA'

新增字段:
ALTER TABLE [表名] ADD [字段名] NVARCHAR (50) NULL

删除字段:
ALTER TABLE [表名] DROP COLUMN [字段名]

修改字段:
ALTER TABLE [表名] ALTER COLUMN [字段名] NVARCHAR (50) NULL

查询表/视图字段、字段类型、字段长度
SELECT name,type_name(xtype) AS type,length,(type_name(xtype)+'('+CONVERT(varchar,length)+')') as t
FROM syscolumns
WHERE (id = OBJECT_ID('表名或者视图名'))

重命名表:(Access 重命名表,请参考文章:在Access数据库中重命名表)
sp_rename '表名', '新表名', 'OBJECT'

新建约束:
ALTER TABLE [表名] ADD CONSTRAINT 约束名 CHECK ([约束字段] <= '2000-1-1')

删除约束:
ALTER TABLE [表名] DROP CONSTRAINT 约束名

新建默认值
ALTER TABLE [表名] ADD CONSTRAINT 默认值名 DEFAULT '51WINDOWS.NET' FOR [字段名]

删除默认值
ALTER TABLE [表名] DROP CONSTRAINT 默认值名

删除Sql Server 中的日志,减小数据库文件大小
dump transaction 数据库名 with no_log
backup log 数据库名 with no_log
dbcc shrinkdatabase(数据库名)
exec sp_dboption '数据库名', 'autoshrink', 'true'

\'添加字段通用函数
Sub AddColumn(TableName,ColumnName,ColumnType)
Conn.Execute("Alter Table "&TableName&" Add "&ColumnName&" "&ColumnType&"")
End Sub

\'更改字段通用函数
Sub ModColumn(TableName,ColumnName,ColumnType)
Conn.Execute("Alter Table "&TableName&" Alter Column "&ColumnName&" "&ColumnType&"")
End Sub

\'检查表是否存在

sql="select count(*) as dida from sysobjects where id = object_id(N'[所有者].[表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"

set rs=conn.execute(sql)

response.write rs("dida")'返回一个数值,0代表没有,1代表存在

判断表的存在:
select * from sysobjects where id = object_id(N'[dbo].[tablename]') and OBJECTPROPERTY(id, N'IsUserTable') = 1

某个表的结构
select * from syscolumns where id = object_id(N'[dbo].[你的表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1

你可能感兴趣的:(sql的一些基本操作(创建表、删除表、增加字段))