如何在ironpython中为Microsoft.SqlServer.SMO.脚本编写器。脚本等级

2024-10-04 11:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用下面的ironpython代码编写数据库对象的脚本:

import sys
import clr

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO


db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # TypeError: expected Array[Urn], got Table
        scripter.Script(table)    

执行此代码时,我得到以下错误:

^{pr2}$

在SMO脚本编写器.文档提供了以下信息:

Script(self: Scripter, urns: Array[Urn]) -> StringCollection
Script(self: Scripter, list: UrnCollection) -> StringCollection
Script(self: Scripter, objects: Array[SqlSmoObject]) -> StringCollection

我尝试创建数组[Urn]或数组[SqlSmoObject],但没有成功。在

有人知道我如何为SMO.Scripter.Script班级?在

我想用python编写下面的VB代码。 取自:http://msdn.microsoft.com/en-us/library/ms162160(v=SQL.90).aspx

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Scripter object and set the required scripting options.
Dim scrp As Scripter
scrp = New Scripter(srv)
scrp.Options.ScriptDrops = False
scrp.Options.WithDependencies = True
'Iterate through the tables in database and script each one. Display the script.
'Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Dim tb As Table
Dim smoObjects(1) As Urn
For Each tb In db.Tables
    smoObjects = New Urn(0) {}
    smoObjects(0) = tb.Urn
    If tb.IsSystemObject = False Then
        Dim sc As StringCollection
        sc = scrp.Script(smoObjects)
        Dim st As String
        For Each st In sc
            Console.WriteLine(st)
        Next
    End If
Next

Tags: thedbserverasscripttbdatabasesrv
2条回答

从未使用过IronPython或SMO,但看起来它需要某种类型的集合。您是否尝试过:

scripter.Script(database.Tables)

而不是一次编写一个表的脚本?在

我找到了解决办法:

arg=System.Array[SMO.SqlSmoObject]([table])

完整脚本如下所示:

^{pr2}$

相关问题 更多 >