数据库升级脚本
场景; 使用测试库完成表设计及功能设计后, 存储过程, 表结构如何同步到正式库去, 需要根据相应日期打包升级.
用法: (脚本执行有先后顺序, 表结构, 索引,触发器,函数. 从底倒上)
--2、表 EXEC [sp_MakeScripts] 'u', '[A-Z][0-9]%', '2017-08-01' --3、索引 EXEC [sp_MakeScripts] 'i', '[A-Z][0-9]%', '2017-08-01' --5、触发器 EXEC [sp_MakeScripts] 'TR', '%', '2017-08-01' --6、函数 EXEC [sp_MakeScripts] 'fn', '%', '2017-08-01' --7、视图 EXEC [sp_MakeScripts] 'V', '%', '2017-08-01' --8、过程 EXEC [sp_MakeScripts] 'P', '%', '2017-08-01'
存储过程:
/*----------------------------------------------------------*/ /* [sp_MakeScripts] */ /*----------------------------------------------------------*/ IF EXISTS ( SELECT 1 FROM sys.objects o WHERE object_id = object_id( N'[sp_MakeScripts]' ) AND OBJECTPROPERTY( object_id, N'IsProcedure') = 1 ) DROP PROCEDURE [sp_MakeScripts] GO CREATE PROC [dbo].[sp_MakeScripts] ( @Type nvarchar(256), --表'U' 索引'I' 函数'FN' 视图'V' 触发器'TR' 过程'P' @objname nvarchar(776) = 'A[0-2]%', @CreateDate DATETIME='1900-01-01' ) as BEGIN /* 功能:主要用于生成升级脚本 参数: @Type 生成的类型 表'U' 索引'I' 函数'FN' 视图'V' 触发器'TR' 过程'P' @objname 数据库中的表名如果结尾是%,则取全部相似的表 @CreateDate 大于或等于@CreateDate后创建的脚本 调用: --1、表 EXEC [sp_MakeScripts] 'u', 'b1%', '2015-01-12' --2、索引及主键 EXEC [sp_MakeScripts] 'i', 'b1%', '2015-01-12' --4、触发器 EXEC [sp_MakeScripts] 'TR', '%', '2015-01-12' --5、函数 EXEC [sp_MakeScripts] 'fn', '%', '2015-01-12' --6、视图 EXEC [sp_MakeScripts] 'V', '%', '2015-01-12' --7、过程 EXEC [sp_MakeScripts] 'P', '%', '2015-01-12' */ SET NOCOUNT ON declare @TableName nvarchar(128) declare @Scripts nvarchar(max) declare @i INT DECLARE @newtypename nvarchar(256) DECLARE @Types TABLE([Type] nvarchar(256)) IF @Type='I' BEGIN INSERT INTO @Types SELECT 'U' END ELSE IF @Type='FN' BEGIN INSERT INTO @Types SELECT 'FN' UNION ALL SELECT 'IF' UNION ALL SELECT 'TF' END ELSE BEGIN INSERT INTO @Types SELECT @Type END declare crs_Table cursor local for SELECT o.name, o.[type] FROM sys.all_objects o, @Types t WHERE o.[type] = t.[Type] COLLATE Chinese_PRC_CI_AS and o.is_ms_shipped = 0 AND o.name like @objname AND O.create_date>=@CreateDate ORDER BY o.name open crs_Table fetch next from crs_Table into @TableName, @newtypename while( @@fetch_status = 0 ) begin IF @Type='I' BEGIN PRINT 'exec [sp_indexGet] '''+@TableName+''', ''d'', 1' print 'go' exec [sp_indexGet] @TableName, 'c' END ELSE IF @Type='U' BEGIN exec [sp_ObjectScriptsGet] @newtypename, @TableName, @Scripts output set @i = 0 while( @i <= len( @Scripts ) / 4000 ) begin print substring( @Scripts, @i * 4000 + 1, 4000 ) select @i = @i + 1 end print 'go' END ELSE BEGIN EXEC sp_TextGet @TableName END fetch next from crs_Table into @TableName, @newtypename end close crs_Table deallocate crs_Table SET NOCOUNT OFF end GO
在未知中徜徉,
求心之荡漾。