通过sql语句创建表

2025-03-06 03:00:37
推荐回答(2个)
回答1:

if exists (select 1
   from sys.sysreferences r join sys.sysobjects o on (o.id = r.constid and o.type = 'F')
   where r.fkeyid = object_id('pro') and o.name = 'FK_PRO_REFERENCE_TEAINF')
alter table pro
   drop constraint FK_PRO_REFERENCE_TEAINF
go

if exists (select 1
            from  sysobjects
           where  id = object_id('pro')
            and   type = 'U')
   drop table pro
go

if exists (select 1
            from  sysobjects
           where  id = object_id('teainf')
            and   type = 'U')
   drop table teainf
go

if exists (select 1
   from  sysobjects where type = 'D'
   and name = '高级'
   )
   drop default 高级
go

/*==============================================================*/
/* Default: 高级                                                  */
/*==============================================================*/
create default 高级
    as '高级'
go

/*==============================================================*/
/* Table: pro                                                   */
/*==============================================================*/
create table pro (
   政务号                  int                  not null,
   工号                   int                  not null,
   姓名                   char(20)             null,
   职称                   char(10)             not null
      constraint CKC_职称_PRO check (职称 in ('高级')),
   教研室                  varchar(16)          not null
      constraint CKC_教研室_PRO check (教研室 in ('软件工程','物联网','数字工程')),
   constraint PK_PRO primary key (政务号),
   constraint AK_UQ_KEY_2_PRO unique (姓名)
)
go

execute sp_bindefault 高级, 'pro.职称'
go

/*==============================================================*/
/* Table: teainf                                                */
/*==============================================================*/
create table teainf (
   工号                   int                  not null
   constraint PK_PRO_1 primary key (工号)
)
go

alter table pro
   add constraint FK_PRO_REFERENCE_TEAINF foreign key (工号)
      references teainf (工号)
go

在Sql Server2008上实验通过,为了外键能使用,所以多建了一个teainf表

回答2:

create table pro(
政务号 int primary key;
工号 int not null;

姓名 char(20) unique;
职称 char(10) default ‘高级’ not null;
教研室 varchar(16) not null;
foreign key(工号) references teainf(工号);
check(教研室 in('软件工程','物联网','数字媒体'));