sqlserver 数据库通用更新脚本操作

it2022-05-05  132

  由于项目功能增加、修改必然要对数据库表、字段、存储过程、函数等修改,现在把项目中通常用到的操作总结下:

  1.给表添加字段  

   if not exists(select 1 from sysobjects a, syscolumns bwhere a.ID=b.ID and a.Name='表名' and a.xtype='U' and b.Name='增加字段名称')    

    Alter TABLE 表名 Add 增加字段名称 类型 null;

  2.表中某一个字段修改长度  

    -- 修改某一个字段nvarchar 类型为最大长度    if exists(select b.Length from sysobjects a, syscolumns b where a.ID=b.ID and a.Name='表名' and a.xtype='U' and b.Name='字段名称' and b.Length > 0)

      alter table 表名 alter column 字段名称 nvarchar(max)    GO    --如果字段长度小于255,就修改字段长度为255    if exists(select b.Length from sysobjects a, syscolumns b  where a.ID=b.ID and a.Name='表名' and a.xtype='U' and b.Name='字段名称' and b.Length < 255*2) 

      alter table 表名 alter column 字段名称 nvarchar(255)    GO

  3.修改表字段类型   

    if exists(select 1 from sysobjects a, syscolumns bwhere a.ID=b.ID and a.Name='表名' and a.xtype='U' and b.Name='字段名称')      Alter TABLE 表名 ALTER COLUMN 字段名称 类型    GO

  4.创建新表,如果数据库中存在新表 先删除,再创建    

    if not exists(select 1 from sysobjects where Name='表名' and xtype='U')    BEGIN     CREATE TABLE 表名     (       字段名称 类型     )    END    GO

  5.创建新存储过程,先删除,后创建 

    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'存储过程名称') AND type in (N'P', N'PC'))    DROP PROCEDURE [dbo].[存储过程名称]    SET ANSI_NULLS ON    GO    SET QUOTED_IDENTIFIER ON    GO    CREATE PROCEDURE [dbo].[存储过程名称]     @参数 类型     AS    BEGIN

          END    GO

  6.创建新函数,先删除,再创建 

    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[函数名称]') AND TYPE in (N'FN', N'IF', N'TF'))    DROP FUNCTION [dbo].[函数名称]

    SET ANSI_NULLS ON    GO    SET QUOTED_IDENTIFIER ON    GO    CREATE function [dbo].[函数名称](     @参数 类型    )

转载于:https://www.cnblogs.com/huashengdoujiao/p/9829339.html

相关资源:项目实施工具-SQL语句生成(insert,Update)

最新回复(0)