zoukankan      html  css  js  c++  java
  • SQL中改变列的数据类型

    一、该列非主键、无default约束

    直接更新:

    alter table 表名 alter column 列名 数据类型

    二、该列为主键列、无default约束

    (1)删除主键

    alter table 表名 drop constraint 主键名称

    (2)更新数据类型

    alter table 表名 alter column 列名 数据类型 not null

    (3)添加主键

    alter table 表名 add constraint 主键名称 primary key (主键字段1,主键字段2)

    三、该列为主键列,有default约束

    (1)删除主键

    alter table 表名 drop constraint 主键名称

    (2)解除default约束

    USE 数据库名
    IF EXISTS (SELECT name FROM sysobjects
    WHERE name = 'default约束名' 
    AND type = 'D')
    BEGIN 
    EXEC sp_unbindefault '数据表.字段'
    END
    GO

    (3)更新数据类型

    alter table 表名 alter column 列名 数据类型 not null

    (4)添加主键

    alter table 表名 add constraint 主键名称 primary key (主键字段1,主键字段2)

    辅助语句:

    (1)找出字段约束名称并赋值到变量中

    declare @name varchar(50)
    select  @name =b.name from sysobjects b join syscolumns a on b.id = a.cdefault 
    where a.id = object_id('表名') 
    and a.name ='列名'

    (2)将字段绑定到用户自定义的数据类型,并不影响现有绑定(使用futureonly)

    此示例将默认值 def_ssn 绑定到用户定义的数据类型 ssn。因为已指定 futureonly,所以不影响类型 ssn 的现有列。
    USE 数据库名
    EXEC sp_bindefault '列名', '自定义数据类型', 'futureonly'

  • 相关阅读:
    278.First Bad Version
    277. Find the Celebrity
    256.Paint House
    276. Paint Fence
    275. H-Index II
    274. H-Index
    273. Integer to English Words
    272. Closest Binary Search Tree Value II
    270. Closest Binary Search Tree Value
    271. Encode and Decode Strings
  • 原文地址:https://www.cnblogs.com/yi-ye/p/5566758.html
Copyright © 2011-2022 走看看