利用SQLDMO生成对象脚本

前段时间公司要开始对数据库的对象进行版本控制,因此经常需要将数据库里的SP、Table的脚本导出到以对象名命名的文件里,如果通过企业管理器来做的话,光是找到这些SP就够麻烦的了,导出来的文件名还不是标准格式,非常的麻烦。
因此就想到用SQLDMO来写一个脚本,来实现上面的功能。
脚本代码如下:
Option   Explicit
Dim  dmoServer
Dim  dmoDB
Dim  dmoSP

Dim  FSO
Dim  strFolder
Dim  strFile

Dim  strNames  ' 需要生成脚本的SP的名称列表,为空生成所有的SP的脚本(所有的名称都以"|"结束)
strNames  =   " |sp_a|sp_b| "
' strNames = ""

Dim  strDBs_NO  ' 不需要生成脚本的数据库列表
strDBs_NO  =   " |master|msdb|tempdb|Northwind|pubs|models| "

Dim  strDBs  ' 需要生成脚本的数据库列表,为空则生成除strDBs_NO包含的数据库外的其他数据库的脚本
strDBs  =   " |UserDB| "

Const  SQLDMOScript_DRI_PrimaryKey  =   268435456
Const  SQLDMOScript_DRI_ForeignKeys  =   134217728
Const  SQLDMOScript_OwnerQualify  =   262144
Const  SQLDMOScript_IncludeHeaders  =   131072
Const  SQLDMOScript_NoDRI  =   512
Const  SQLDMOScript_AppendToFile  =   256
Const  SQLDMOScript_Default  =   4
Const  SQLDMOScript_Drops  =   1
Const  SQLDMOScript_ToFileOnly  =   64

Set  dmoServer  =   CreateObject ( " SQLDMO.SQLServer " )
Set  FSO  =   CreateObject ( " Scripting.FileSystemObject " )

dmoServer.LoginSecure 
=   False
dmoServer.Connect 
" ServerName_here " " uid_here " " pwd_here "

For   Each  dmoDB In dmoServer.Databases
    strFolder 
=   " StoreFolder_here "   &  dmoDB.Name
    
    
If  ( Instr ( 1 ,strDBs_NO, " | " + dmoDB.Name + " | " =   0   or  strDBs_NO  =   ""  )  And  ( Instr ( 1 ,strDBs, " | " + dmoDB.Name + " | " >   0   or  strDBs  =   "" Then
      
If   Not  FSO.FolderExists(strFolder)  Then  
        FSO.CreateFolder(strFolder)
      
End   If
        
      
For   Each  dmoSP In dmoDB.StoredProcedures
        
If   Not  dmoSP.SystemObject  And  (  Instr ( 1 , " | " + strNames,dmoSP.Name + " | " >   0   or  strNames  =   ""  )  Then
          strFile 
=  strFolder  &   " "   &  dmoSP.Name  &   " .sql "
          
' dmoSP.Script SQLDMOScript_IncludeHeaders + SQLDMOScript_ToFileOnly + SQLDMOScript_Drops + SQLDMOScript_Default , strFile  '选项可以根据需要增删,具体可参见前面定义的Const
   dmoSP.Script SQLDMOScript_IncludeHeaders  +  SQLDMOScript_ToFileOnly  +  SQLDMOScript_Default , strFile 
 
End   If
      
Next       
    
End   If
Next

Set  dmoSP  =   Nothing
Set  dmoDB  =   Nothing
Set  dmoServer  =   Nothing  
有了这脚本以后,不管是抓整个数据库里所有SP的脚本,还是指定的几个SP的脚本,都变得非常的简单了。
注:表的脚本只要稍做修改就可以。(dmoDB.StoredProcedures改成Tables)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值