我需要使用SMO在代码中生成脚本,因此这与使用Management Studio手动创建脚本完全相同。即数据库->任务->生成脚本。->选择架构和数据。
因此,我希望拥有类似的东西:
USE [master]
GO
CREATE DATABASE [MyDatabase]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'MyDatabase', FILENAME = N'C:\Databases\Data\MyDatabase.mdf' , SIZE = 100KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'MyDatabase_log', FILENAME = N'C:\Databases\Data\MyDatabase_log.ldf' , SIZE = 100KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [MyDatabase] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
BEGIN
EXEC [MyDatabase].[dbo].[sp_fulltext_database] @action = 'enable'
END
GO
ALTER DATABASE [MyDatabase] SET ANSI_NULL_DEFAULT OFF
...
GO
/****** Object: DatabaseRole [StoreRW] Script Date: 22.02.2019 10:14:14 ******/
CREATE ROLE [StoreRW]
GO
...
GO
CREATE TABLE [dbo].[MyTabale1](
...
即结果应包含CREATE DATABASE
语句。
但是目前我还没有成功。我有数据库架构和数据,但没有CREATE DATABASE
。
我正在使用以下代码:
$My="$ms.Management.Smo" #
$s = new-object ("$My.Server") $DataSource
if ($s.Version -eq $null) { Throw "Can't find the instance $Datasource" }
$ver = $s.Version
echo " SQL Server version is $ver"
$db= $s.Databases[$Database]
if ($db.name -ne $Database) { Throw "Can't find the database '$Database' in $Datasource" };
$transfer = new-object ("$My.Transfer") $db
if ($transfer -eq $null) { Throw "Can't create transfer object" }
$transfer.Options.Default = $true;
$transfer.Options.ScriptBatchTerminator = $true # this only goes to the file
$transfer.Options.ToFileOnly = $true # this only goes to the file
$transfer.Options.ExtendedProperties = $true;
$transfer.Options.IncludeDatabaseContext = $true;
$transfer.Options.WithDependencies = $true;
$transfer.Options.IncludeHeaders = $true;
$transfer.Options.SchemaQualify = $true;
$transfer.Options.DriAll = $true;
$transfer.Options.ScriptData = $true;
$transfer.Options.ScriptSchema = $true;
$transfer.Options.FileName = $BackupFile;
$tmp = $transfer.Options;
echo " Transfer options are: $tmp";
$transfer.EnumScriptTransfer();
echo "Scripting database '$dbName' to '$BackupFile' done"
我还需要添加什么才能将CREATE DATABASE
加入其中?
答案 0 :(得分:1)
分配了$db
后,需要添加此行:
$db.script()
如果要将脚本数据输出到文件,则只需添加以下内容:
$db.script() | out-file "c:\folder\create-db.sql"