对以下内容进行了测试:
- Win 7.0,.NET 4.0,VS 2010,SQL Server 2008R2
- Win 7.0,.NET 4.6.1,VS 2017,SQL Server 2014
所需的程序集引用:
- microsoft.SqlServer.ConnectionInfo
- microsoft.SqlServer.Management.Sdk.Sfc
- microsoft.SqlServer.Smo
我使用“确定”按钮创建了一个简单的Win Forms应用程序,并调用了以下功能。
注意:如果要脚本化视图,则需要添加
if( myView.IsSystemObject == true ) continue;
确保未编写系统视图的脚本;我还没有测试。对于旧版本的SQL Server,您可能还需要检查表。
public static string ScriptDatabase( string dbConnectionString, string databaseName ){ SqlConnection cOnn= new SqlConnection( dbConnectionString ); ServerConnection serverCOnn= new ServerConnection( conn ); var server = new Server( serverConn ); var database = server.Databases[ databaseName ]; var scripter = new Scripter( server ); scripter.Options.IncludeIfNotExists = true; scripter.Options.ScriptSchema = true; scripter.Options.ScriptData = true; string scrs = ""; foreach( Table myTable in database.Tables ) { foreach( string s in scripter.EnumScript( new Urn[] { myTable.Urn } ) ) scrs += s + "\n\n"; ; } return ( scrs );}
函数将如下调用:
// Connection string for local SQL Server default instanceScriptDatabase( "Server=.;Database=PlayGround;Trusted_COnnection=True;", "PlayGround" );
输出:
SET ANSI_NULLS ONSET QUOTED_IDENTIFIER ONIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tBlah]') AND type in (N'U'))BEGINCREATE TABLE [dbo].[tBlah]( [ID] [int] IDENTITY(1,1) NOT NULL, [tID] [varchar](20) COLLATE Latin1_General_CI_AS NULL, [Value] [varchar](20) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]ENDSET IDENTITY_INSERT [dbo].[tBlah] ONINSERT [dbo].[tBlah] ([ID], [tID], [Value]) VALUES (1, N'2', N'1234')INSERT [dbo].[tBlah] ([ID], [tID], [Value]) VALUES (2, N'2', N'345.6')
MSDN参考:
- Microsoft.SqlServer.Management.Smo.Scripter
- Microsoft.SqlServer.Management.Common.ServerConnection
- Microsoft.SqlServer.Management.Smo.Server
- Microsoft.SqlServer.Management.Smo.Database
检查最新的.NET版本; 添加了必需的参考;清理示例代码;添加了示例conn字符串