SQL 对 SQLServer 的一些简单基础操作



添加约束

--添加主键约束

                       alter table 表名add constraint 约束名 primary key(要设为主键的列名)

--添加唯一约束

                       alter table 表名add constraint 约束名 unique(stuName)

--添加检查约束:

                       alter table 表名add constraint 约束名 check(条件,如:stuSex='男' or stuSex='女')

--添加默认约束:

                       alter table 表名add constraint 约束名 default(要设置的默认值) for stuSex

--添加外键约束:

                       alter table 表名add constraint 约束名 foreign key(本表的列名) references 主键表名(列名)


一个简单的例子  包括创建数据库  外键  约束  check  改类型

create database ytf
use ytf
go
/*建S表*/
create table S(Sno char(10) primary key,Sname char(10),Status int,City char(10))
/*建P表*/
create table P(Pno char(10) primary key,Pname char(10),Color int,Weight int)
/*建J表*/
create table J(Jno char(10) primary key,Jname char(10),City char(10))
/*建J表 外键的建立*/
create table JPS(Pno char(10),Jno char(10),Sno char(10),QTY char(10),
primary key(Pno,Jno,Sno),
Foreign Key (Pno) references P(Pno),
Foreign Key (Jno) references J(Jno),
Foreign Key (Sno) references S(Sno))
/*为SPJ表增加一供应日期列,列名为SUPDATE,日期型*/ 
alter table JPS add SupDate date
/*为S、P、J表的SNAME、PNAME、JNAME列定义UNIQUE约束;约束名分别命名为UQ_SNAME, UQ_PNAME,UQ_JNAME;*/ 
alter table S add constraint UQ_SNAME unique(Sname)
alter table P add constraint UQ_PNAME unique(Pname)
alter table J add constraint UQ_JNAME unique(Jname)
/*实现DATE属性的Check(检查)约束: SUPDATE<getdate()*/ 
alter table JPS add constraint cons_date_chk check(SupDate<getdate())
/*删除P表PNAME列的唯一性约束*/ 
alter table P drop constraint UQ_PNAME
/*将P表中PNAME列的数据类型改为可变字符串型*/
alter table P alter column Pname varchar(50) 
/*用SQL语言在SPJ表上建立一个唯一性索引。*/
create unique index ytf on JPS (QTY)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ftytotop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值