使用powershell生成SQL创建表脚本
我希望使用powershell能够使用create table语句快速生成SQL脚本,这些语句能够在现有数据库中重新创建所有表。唯一的问题是我想调整一些选项,比如关闭身份 我就是不知道该怎么做 我已经设置了一个$server变量,并设置了一个名为$tables的变量来获取特定数据库中的所有表。 然后我使用一个循环: foreach($tables中的table) {$table.Script() } 这是可行的,但我不知道如何添加脚本选项,比如NoIdentities=$True使用powershell生成SQL创建表脚本,powershell,Powershell,我希望使用powershell能够使用create table语句快速生成SQL脚本,这些语句能够在现有数据库中重新创建所有表。唯一的问题是我想调整一些选项,比如关闭身份 我就是不知道该怎么做 我已经设置了一个$server变量,并设置了一个名为$tables的变量来获取特定数据库中的所有表。 然后我使用一个循环: foreach($tables中的table) {$table.Script() } 这是可行的,但我不知道如何添加脚本选项,比如NoIdentities=$True 有人能帮我吗?
有人能帮我吗?我曾经不得不做很多重复的类型工作,包括为 数据库中的每个表。因此,我开发了一种通用工具,适用于这类工作。我包括了工具的原样,以及一个用于 为每个表和每个数据库用户类别生成一系列grant命令 我的工具使用CSV文件,而不是直接使用数据库。我发现为许多不同的任务生成CSV文件和模板相当容易。您的里程可能会有所不同。也许你可以从这个工具开始,根据你的需要调整它 这是工具和一个示例运行
<#
.SYNOPSIS
Generates multiple expansions of a template,
driven by data in a CSV file.
.DESCRIPTION
This function is a table driven template tool.
It generates output from a template and
a driver table. The template file contains plain
text and embedded variables. The driver table
(in a csv file) has one column for each variable,
and one row for each expansion to be generated.
#>
function Expand-csv {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $driver,
[Parameter(Mandatory=$true)]
[string] $template
)
Process
{
$xp = (Get-Content $template) -join "`r`n"
Import-Csv $driver | % {
$_.psobject.properties | % {Set-variable -name $_.name -value $_.value}
$ExecutionContext.InvokeCommand.ExpandString($xp)
}
}
}
# Now do a sample run of Expand-csv
# then display inputs and output
Expand-csv grants.csv grants.tmplt > grants.sql
get-content grants.tmplt
import-csv grants.csv
get-content grants.sql
在现实生活中,我在$profile文件中定义了该工具,因此无论何时我在powershell中都可以使用它
我不确定这对你的案子有多适用。这并不能解决您所描述的确切情况,但您可以采用这种技术。如果您仍在寻找解决方案,我建议您使用我在单个表中使用的这个小脚本。您应该能够相当轻松地更新它以支持多个表。请注意下面的行“$scripter.Options.NoIdentities=$true;” 将其保存到“table.ps1”并通过传递参数值从PowerShell中执行:
& table.ps1 -server SERVER\INSTANCE -database MyDB -schema dbo -table MyTable
让我知道它是否有效
param
(
[string] $server,
[string] $database,
[string] $schema,
[string] $table
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
$db = $srv.Databases[$database]
$tbl = $db.tables | Where-object {$_.schema -eq $schema-and$_.name -eq $table}
$scripter.Options.ScriptSchema = $true;
$scripter.Options.ScriptData = $false;
$scripter.Options.NoCommandTerminator = $false;
$scripter.Options.NoCollation = $true;
$scripter.Options.NoIdentities = $true;
$scripter.EnumScript($tbl)
& table.ps1 -server SERVER\INSTANCE -database MyDB -schema dbo -table MyTable