Home > php教程 > php手册 > mssql alter table 的用法

mssql alter table 的用法

WBOY
Release: 2016-06-06 20:00:21
Original
1217 people have browsed it

mssql 的alter table 命令提供了很多很强大的功能,本文的主要目的是记录下来笔者在使用过程中遇到的一些, 为了方便以后的查询。 1. 对constraint的修改, alter table 没有 alter constraint 属性,所以只能是先drop constraint, 再add constraint.alter t

mssql 的alter table 命令提供了很多很强大的功能,本文的主要目的是记录下来笔者在使用过程中遇到的一些,

为了方便以后的查询。


1.  对constraint的修改,

alter table 没有 alter constraint 属性,所以只能是先drop constraint, 再add constraint.

alter table [table_name] drop constraint [constraint_name]

alter table [table_name] add constraint [constraint_name] [constraint_content]

Copy after login


2. 增加一列

alter table [table_name] add column [column_name] [column_type]

Copy after login


3. 对某列加default 值

这个实际上是属于add constraint的一部分, 不过是比较特殊的一种,所以单独列出来

alter table [table_name] add constraint [constraint_name] default [default value] for [column]

Copy after login


4. 给某列加identity 或者清零

MSSQL本身不提供这样的功能,但是可以通过把某列删除,再创建的方式来实现

alter table [table Name] drop column [column name]

alter table [table Name ]add [column name] int identity(1,1) not null.
Copy after login


清零

DBCC CHECKIDENT (【table name】, RESEED, 1)
Copy after login



这种方式也可以实现identity的清零。


5. 给某列加primary key

alter   table   table_name     drop   constraint   pk_name

alter   table   table_name   add   constraint   pk_name   primary   key   (column name)
Copy after login



6. 给表加外键

ALTER TABLE 【table name 】
ADD CONSTRAINT [constraint name] FOREIGN KEY ([column name])
    REFERENCES [reference table ] (reference column name ) ;
ALTER TABLE [table name ]
DROP CONSTRAINT [refence constraint name] ;
Copy after login


7. 如何给一个表的某列改名啊

这里使用的就不是alter ,而是MSSQL提供的了个sp_rename的SP。

sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name' 
    [ , [ @objtype = ] 'object_type' ] 
Copy after login

这里objtype 可以选择如下:

 

Value

Description

COLUMN

A column to be renamed.

DATABASE

A user-defined database. This object type is required when renaming a database.

INDEX

A user-defined index.

OBJECT

An item of a type tracked in sys.objects. For example, OBJECT could be used to rename objects including constraints (CHECK, FOREIGN KEY, PRIMARY/UNIQUE KEY), user tables, and rules.

USERDATATYPE

An alias data type or CLR User-defined Types added by executing CREATE TYPE or sp_addtype.

举个例子吧, 对表tblTable 的一列a ,改名为b

exec sp_rename 'dbo.tblTable.a', 'b', 'COLUMN'
Copy after login



未完,待续

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template