最近想全面了解下SQL中的东西,想操作下约束 我手动建了表student 有两个字段 id,age 都为int型,其中id是主键,age的默认值是0  ,手动建完后查看脚本如下:
USE [A]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[student](
[id] [int] NOT NULL,
[age] [int] NOT NULL CONSTRAINT [DF_student_age]  DEFAULT ((0)),
 CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED 
(
[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]我现在想用脚本将字段age改为varchar型的,并且默认值为'0' ,我写了下面的脚步系统提示不行
alter table student alter column age [varchar] (200)这里好像要首先删除age上的约束,然后再操作,怎么写一个SQL实现我的所要呢 ??
 

解决方案 »

  1.   

    CREATE TABLE [dbo].[student](
    [id] [int] NOT NULL,
    [age] [int] NOT NULL CONSTRAINT [DF_student_age] DEFAULT ((0)),
     CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED  
    (
    [id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]--1
    alter table [student] drop constraint [DF_student_age]
    go
    --2
    alter table student alter column age [varchar] (200)
    go
    --3.
    alter table [student] add constraint [DF_student_age] default '0' for age
    go看错。这样
      

  2.   


    alter table [dbo].[student] drop CONSTRAINT DF_student_age
    alter table [dbo].[student] alter column age varchar(200) 
    alter table [dbo].[student] add CONSTRAINT DF_student_age DEFAULT '' for age