Sql server 如何编写所有模式绑定视图(以及其他阻止表截断的对象,如“筛选索引”)的脚本?

Sql server 如何编写所有模式绑定视图(以及其他阻止表截断的对象,如“筛选索引”)的脚本?,sql-server,sql-server-2012,Sql Server,Sql Server 2012,如何编写所有架构绑定视图的脚本 另一方面,父问题是模式绑定视图(以及筛选索引)破坏了SSMA(SQL SERVER Migration Assistant)数据导入,因为SSMA具有奇怪且不可配置的行为:在导入之前调用truncate table。参与模式绑定视图(索引视图)可防止表截断,其他对象如“筛选索引”。使用SSMS功能生成脚本。在SSMS中,右键单击数据库,转到任务,然后单击生成脚本,您可以选择、查看表等。只需选择所需内容,即可完成操作 有关步骤的详细信息,请阅读此链接 您可以使用它

如何编写所有架构绑定视图的脚本


另一方面,父问题是模式绑定视图(以及筛选索引)破坏了SSMA(SQL SERVER Migration Assistant)数据导入,因为SSMA具有奇怪且不可配置的行为:在导入之前调用truncate table。参与模式绑定视图(索引视图)可防止表截断,其他对象如“筛选索引”。

使用SSMS功能生成脚本。在SSMS中,右键单击数据库,转到
任务
,然后单击
生成脚本
,您可以选择、查看表等。只需选择所需内容,即可完成操作

有关步骤的详细信息,请阅读此链接

您可以使用它来获取特定数据库中所有视图的脚本,并且只能从特定模式中获取

Use [MyDatabase]
SELECT o.name
       ,s.name
       ,OBJECT_DEFINITION(o.object_id) AS Create_script
    FROM sys.objects AS o
    JOIN sys.schemas AS s
        ON o.schema_id = s.schema_id
    WHERE type_desc = 'View'
    AND s.name = 'dbo' --Replace with your schema

改变这一点,只需选择第3列中的所有内容,然后粘贴到记事本++或您选择的其他工具中。只需将文件另存为.sql,脚本就可以运行了。

SMO/powershell解决方案:

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')|Out-Null; 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended')|Out-Null; 
$sr = '<server>'
$ln = '<login>'
$pw = '<password>'
$db = '<database>'

$u = 'Microsoft.SqlServer.Management.Smo'
$n = [Environment]::NewLine;
$s = new-object ($u+'.Server') $sr;
$c = $s.ConnectionContext;$c.LoginSecure=$false;$c.Login=$ln;$c.Password=$pw;
$s.SetDefaultInitFields((new-object ($u+'.View')).getType(), "IsSchemaBound");
$v=$s.Databases[$db].Views|Where-Object{$_.IsSchemaBound -eq $true}
if ($v | where $_.Triggers.Count -gt 0) {throw new-object System.ArgumentException 'Views with triggers are not supported'}
$_createScript = ('SET ARITHABORT ON','SET CONCAT_NULL_YIELDS_NULL ON','SET QUOTED_IDENTIFIER ON','SET ANSI_NULLS ON','SET ANSI_PADDING ON','SET ANSI_WARNINGS ON','SET NUMERIC_ROUNDABORT OFF')+
     ($v | %{$i=$_;(@()+'GO'+($i.Script()|where {$_ -notlike "SET * ON"})+'GO'+ ($i.Indexes|sort IsClustered –desc|%{$_.Script()}| where {$_ -notlike "SET *"}))})
$_dropScript =  $v | %{$_.Script(( new-object ($u+'.ScriptingOptions') -prop @{ScriptDrops =$true}))}
Write-Host (@()+'/*'+$_dropScript+'*/'+('-' * 40)+ $_createScript -join $n)
剧本:

DECLARE @OUTPUT TABLE (id int identity(1,1), line nvarchar(max))
DECLARE @cmd VARCHAR(8000), @psAlterSP VARCHAR(8000),  @psGetDatabase VARCHAR(8000), @psGetViews VARCHAR(8000), @psGetFilteredIndexes VARCHAR(8000), @psLoadAssemblies VARCHAR(8000), @script nvarchar(max) ='',
    @psCompose1 VARCHAR(8000), @psCompose2 VARCHAR(8000), @psCompose3 VARCHAR(8000), @psCompose4 VARCHAR(8000), @psCompose5 VARCHAR(8000), @psComposeAll VARCHAR(8000)
DECLARE @sr nvarchar(max)='<server>', 
        @ln nvarchar(max)='<loginname>', 
        @pw nvarchar(max)='<password>', 
        @db nvarchar(max)=DB_NAME(),
        @sp sysname = 'ManageObjectsThatPreventTruncate',
        @ss sysname = 'dbo'
SET @psLoadAssemblies  = '[System.Reflection.Assembly]::LoadWithPartialName(''Microsoft.SqlServer.SMO'')|Out-Null;$ErrorActionPreference = ''Stop'';'
SET @psGetDatabase='$u =''Microsoft.SqlServer.Management.Smo'';$n = [Environment]::NewLine;$a = ''''+[char]39;$s = new-object ($u+''.Server'') $sr;$c = $s.ConnectionContext;$c.LoginSecure=$false;$c.Login=$ln;$c.Password=$pw;$s.SetDefaultInitFields((new-object ($u+''.View'')).getType(),''IsSchemaBound'');$d = $s.Databases[$db];'
SET @psGetDatabase=REPLACE(@psGetDatabase,'$sr',''''+@sr+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$ln',''''+@ln+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$pw',''''+@pw+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$db',''''+@db+'''')
SET @psGetViews = '$v=$d.Views|where {$_.IsSchemaBound -eq $true};if ($v | where {$_.Triggers.Count -gt 0}) {throw new-object System.ArgumentException ''Views with triggers are not supported''};'
SET @psGetFilteredIndexes = '$r = $d.ExecuteWithResults(''SELECT object_id, Name FROM sys.indexes WHERE has_filter=1 ORDER BY object_id, Name'');$x = @();foreach ($i in $r.Tables[0].Rows) {$x+=$d.Tables.ItemById($i[0]).Indexes[$i[1]]};'
SET @psCompose1='$o1=(''BEGIN TRY'',''IF @drop=1'',''BEGIN'')+($v | %{$_s=$_.Schema;$_n=$_.Name; \"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_n'') DROP VIEW [$_s].[$_n]\"})+($x | %{$_s=$_.Parent.Schema;$_tn=$_.Parent.Name;$_in=$_.Name; \"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_tn'') and (@indexName is null or @indexName=''$_in'') DROP INDEX [$_in] ON [$_s].[$_tn]\"})+''END'';'
SET @psCompose2='$o2=(''ELSE'',''BEGIN'',''SET ARITHABORT ON'',''SET CONCAT_NULL_YIELDS_NULL ON'',''SET QUOTED_IDENTIFIER ON'',''SET ANSI_NULLS ON'',''SET ANSI_PADDING ON'',''SET ANSI_WARNINGS ON'',''SET NUMERIC_ROUNDABORT OFF'',''DECLARE @sql varchar(max)'');'
SET @psCompose3='$o3= ($v | %{$i=$_;$_s=$_.Schema;$_n=$_.Name; (@()+(\"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_n'')\")+''BEGIN''+(''SET @sql =''+$a+(($i.Script()|where {$_ -notlike ''SET * ON''}) -join '''').Replace($a,$a+$a)+$a)  +''exec (@sql)''+( $i.Indexes| sort IsClustered –desc| %{ @()+$n+(''SET @sql =''+$a+(($_.Script()| where {$_ -notlike ''SET *''}) -join '''').Replace($a,$a+$a) +$a) +''exec (@sql)''})+''END'' )});'
SET @psCompose4='$o4= ($x | %{$i=$_;$_s=$_.Parent.Schema;$_tn=$_.Parent.Name;$_in=$_.Name;(@()+(\"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_tn'') and (@indexName is null or @indexName=''$_in'')\")+''BEGIN''+(''SET @sql =''+$a+(($i.Script()|where {$_ -notlike ''SET * ON''}) -join '''').Replace($a,$a+$a)+$a)+''exec (@sql)''+''END'')});'
SET @psCompose5='$o5=(''END'',''END TRY'',''BEGIN CATCH'',''THROW'',''END CATCH'');'
SET @psComposeAll= '$o=($o1+$o2+$o3+$o4+$o5) -join $n;'

SET @psAlterSP = '$p = $d.StoredProcedures[\"$sp\",\"$ss\"]; if($p -eq $null){$p = new-object ($u+''.StoredProcedure'') $d, \"$sp\",\"$ss\";$p.TextHeader=\"CREATE PROCEDURE [$ss].[$sp]$n @drop bit = 0,$n @schema sysname = NULL,$n @name sysname = NULL,$n @indexName sysname=NULL $n AS$n\";$p.TextBody=$o;$p.Create()}else{$p[0].TextBody=$o; $p[0].Alter()}'
SET @psAlterSP=REPLACE(@psAlterSP,'$sp',@sp)
SET @psAlterSP=REPLACE(@psAlterSP,'$ss',@ss)

SET @cmd = 'powershell -Command "'+@psLoadAssemblies+@psGetDatabase+@psGetViews+@psGetFilteredIndexes+@psCompose1+@psCompose2+@psCompose3+@psCompose4++@psCompose5+@psComposeAll+@psAlterSP+'"'
PRINT LEN(@cmd)
DECLARE @result int
INSERT INTO @OUTPUT (line)
exec @result =xp_cmdshell @cmd

IF @result=0 AND (SELECT count(*) FROM @OUTPUT WHERE line is not null)=0
BEGIN
    PRINT 'OK'
END
ELSE
BEGIN
    PRINT 'FAILURE'
    SELECT @script+line FROM @OUTPUT
    WHERE line is not null
    ORDER BY id;
    THROW 50000,'Error during xp_cmdshell execution',1;
END
DECLARE@OUTPUT表(id int-identity(1,1),第nvarchar行(max))
声明@cmd VARCHAR(8000),@psAlterSP VARCHAR(8000),@psGetDatabase VARCHAR(8000),@psGetViews VARCHAR(8000),@psGetFilteredIndexes VARCHAR(8000),@psLoadAssemblies VARCHAR(8000),@script nvarchar(max)='',
@psCompose1 VARCHAR(8000),@psCompose2 VARCHAR(8000),@psCompose3 VARCHAR(8000),@psCompose4 VARCHAR(8000),@psCompose5 VARCHAR(8000),@pscomposelvarchar(8000)
声明@sr nvarchar(最大值)='',
@ln nvarchar(最大值)='',
@pw nvarchar(最大值)='',
@db nvarchar(max)=db_NAME(),
@sp sysname='ManageObjectsThatPreventTruncate',
@ss sysname='dbo'
SET@psLoadAssemblies='[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')| Out Null$ErrorActionPreference=''停止';'
设置@psGetDatabase='$u=''Microsoft.SqlServer.Management.Smo''$n=[Environment]::换行符$a=''''+[char]39$s=新对象($u+''.Server'')$sr$c=s.ConnectionContext美元$c、 LoginSecure=$false$c、 登录名=$ln$c、 密码=$pw$s、 SetDefaultInitFields((新对象($u+''.View'').getType(),''IsSchemabile'')$d=$s.Databases[$db];'
设置@psGetDatabase=REPLACE(@psGetDatabase,'$sr','''''''+@sr+''''')
设置@psGetDatabase=REPLACE(@psGetDatabase,'$ln','''''''+@ln+'')
设置@psGetDatabase=REPLACE(@psGetDatabase,'$pw',''''''+@pw+'')
设置@psGetDatabase=REPLACE(@psGetDatabase,'$db',''''''''+@db+'')
SET@psGetViews='$v=$d.Views |其中{$\.isschemabile-eq$true};如果($v | where{$\.Triggers.Count-gt 0}){抛出新对象System.ArgumentException''不支持带有触发器的视图''};'
设置@psGetFilteredIndexes='$r=$d.ExecuteWithResults(''选择对象id,从sys.indexes中的名称,其中按对象id排序的过滤器=1,名称'')$x=@();foreach($r.Tables[0].行中的i){$x+=$d.Tables.ItemById($i[0])。索引[$i[1]]};'
“开始尝试”、“如果@下降=1”以及“如果如果@下降=1”的,”开始“开始”的,”除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了“开始尝试尝试”外,如果如果如果如果如果如果“开始开始尝试”,如果如果@如果@如果@如果@下降=下降=下降=1”如果如果如果如果如果如果如果如果如果在下降=1”下降=1”下降=1,”,”,”除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了除了null或@Name=''$\u tn'')和(@indexName为null或@indexName=''$\u in'')将索引[$\u in]放到[$\u s].$\u tn\''})+''END'';上
设置@psCompose2=“$o2=”(“ELSE”,“BEGIN”,“SET ARITHABORT ON”,“SET CONCAT_NULL_YIELDS_NULL ON”,“SET QUOTED_IDENTIFIER ON”,“SET ANSI_NULLS ON”,“SET ANSI_PADDING ON”,“SET ANSI_WARNINGS ON”,“SET NUMERIC_ROUNDABORT OFF”,“DECLARE@sql varchar(max)”);“SET ANSI
(5)美国的一些州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州州$n+(''SET@sql=''+$a+(($u.Script()|其中{$u-notlike'SET*'})-join'')。替换($a,$a+$a)+$a)+'exec(@sql)})+'END'});'
(x)美国的一些州的一些州的一些州的一些州的作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为+执行(@sql)“+”END“)};”
设置@psCompose5=“$o5=”(“结束”,“结束尝试”,“开始捕捉”,“抛出”,“结束捕捉”);“
SET@pscomposell='$o=($o1+$o2+$o3+$o4+$o5)-加入$n;'
设置@psAlterSP='$p=$d.StoredProcedures[\“$sp\”,\“$ss\”];如果($p-eq$null){$p=new object($u+'.StoredProcedures'')$d,\“$sp\”,\“$ss\”;$p.TextHeader=\'CREATE procedures[$ss]。$sp]$n@drop bit=0,$n@schema sysname=null,$n@sysname=null,$n@sysname=null,$n作为$n\”;$n;$p.TextBody=$o;$p.CREATE[text0].Alter()}'
设置@psAlterSP=REPLACE(@psAlterSP,$sp',@sp)
设置@psAlterSP=REPLACE(@psAlterSP,$ss',@ss)
SET@cmd='powershell-Command“++@psLoadAssemblies++@psGetDatabase++@psGetViews++@psGetFilteredIndexes++@psCompose1++@psCompose2++@psCompose3++@psCompose4++@psCompose5++@pscomposell++@psAlterSP++”
打印长度(@cmd)
声明@result int
插入@OUTPUT(行)
exec@result=xp\u cmdshell@cmd
如果@result=0且(从@OUTPUT中选择count(*),其中行不为null)=0
开始
打印“OK”
结束
其他的
开始
打印“失败”
从@OUTPUT中选择@script+行
其中行不为空
按id订购;
抛出50000,“xp\u cmdshell执行期间出错”,1;
结束

不可能只选择架构受限的视图,似乎我需要使用SMO编写脚本。这是透视图。它不能解决父问题:编写脚本的视图意味着也要编写脚本索引,并且索引不存在。但似乎不必使用SMO就可以解决问题。。。
DECLARE @OUTPUT TABLE (id int identity(1,1), line nvarchar(max))
DECLARE @cmd VARCHAR(8000), @psAlterSP VARCHAR(8000),  @psGetDatabase VARCHAR(8000), @psGetViews VARCHAR(8000), @psGetFilteredIndexes VARCHAR(8000), @psLoadAssemblies VARCHAR(8000), @script nvarchar(max) ='',
    @psCompose1 VARCHAR(8000), @psCompose2 VARCHAR(8000), @psCompose3 VARCHAR(8000), @psCompose4 VARCHAR(8000), @psCompose5 VARCHAR(8000), @psComposeAll VARCHAR(8000)
DECLARE @sr nvarchar(max)='<server>', 
        @ln nvarchar(max)='<loginname>', 
        @pw nvarchar(max)='<password>', 
        @db nvarchar(max)=DB_NAME(),
        @sp sysname = 'ManageObjectsThatPreventTruncate',
        @ss sysname = 'dbo'
SET @psLoadAssemblies  = '[System.Reflection.Assembly]::LoadWithPartialName(''Microsoft.SqlServer.SMO'')|Out-Null;$ErrorActionPreference = ''Stop'';'
SET @psGetDatabase='$u =''Microsoft.SqlServer.Management.Smo'';$n = [Environment]::NewLine;$a = ''''+[char]39;$s = new-object ($u+''.Server'') $sr;$c = $s.ConnectionContext;$c.LoginSecure=$false;$c.Login=$ln;$c.Password=$pw;$s.SetDefaultInitFields((new-object ($u+''.View'')).getType(),''IsSchemaBound'');$d = $s.Databases[$db];'
SET @psGetDatabase=REPLACE(@psGetDatabase,'$sr',''''+@sr+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$ln',''''+@ln+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$pw',''''+@pw+'''')
SET @psGetDatabase=REPLACE(@psGetDatabase,'$db',''''+@db+'''')
SET @psGetViews = '$v=$d.Views|where {$_.IsSchemaBound -eq $true};if ($v | where {$_.Triggers.Count -gt 0}) {throw new-object System.ArgumentException ''Views with triggers are not supported''};'
SET @psGetFilteredIndexes = '$r = $d.ExecuteWithResults(''SELECT object_id, Name FROM sys.indexes WHERE has_filter=1 ORDER BY object_id, Name'');$x = @();foreach ($i in $r.Tables[0].Rows) {$x+=$d.Tables.ItemById($i[0]).Indexes[$i[1]]};'
SET @psCompose1='$o1=(''BEGIN TRY'',''IF @drop=1'',''BEGIN'')+($v | %{$_s=$_.Schema;$_n=$_.Name; \"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_n'') DROP VIEW [$_s].[$_n]\"})+($x | %{$_s=$_.Parent.Schema;$_tn=$_.Parent.Name;$_in=$_.Name; \"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_tn'') and (@indexName is null or @indexName=''$_in'') DROP INDEX [$_in] ON [$_s].[$_tn]\"})+''END'';'
SET @psCompose2='$o2=(''ELSE'',''BEGIN'',''SET ARITHABORT ON'',''SET CONCAT_NULL_YIELDS_NULL ON'',''SET QUOTED_IDENTIFIER ON'',''SET ANSI_NULLS ON'',''SET ANSI_PADDING ON'',''SET ANSI_WARNINGS ON'',''SET NUMERIC_ROUNDABORT OFF'',''DECLARE @sql varchar(max)'');'
SET @psCompose3='$o3= ($v | %{$i=$_;$_s=$_.Schema;$_n=$_.Name; (@()+(\"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_n'')\")+''BEGIN''+(''SET @sql =''+$a+(($i.Script()|where {$_ -notlike ''SET * ON''}) -join '''').Replace($a,$a+$a)+$a)  +''exec (@sql)''+( $i.Indexes| sort IsClustered –desc| %{ @()+$n+(''SET @sql =''+$a+(($_.Script()| where {$_ -notlike ''SET *''}) -join '''').Replace($a,$a+$a) +$a) +''exec (@sql)''})+''END'' )});'
SET @psCompose4='$o4= ($x | %{$i=$_;$_s=$_.Parent.Schema;$_tn=$_.Parent.Name;$_in=$_.Name;(@()+(\"IF (@schema is null or @schema=''$_s'') and (@name is null or @name=''$_tn'') and (@indexName is null or @indexName=''$_in'')\")+''BEGIN''+(''SET @sql =''+$a+(($i.Script()|where {$_ -notlike ''SET * ON''}) -join '''').Replace($a,$a+$a)+$a)+''exec (@sql)''+''END'')});'
SET @psCompose5='$o5=(''END'',''END TRY'',''BEGIN CATCH'',''THROW'',''END CATCH'');'
SET @psComposeAll= '$o=($o1+$o2+$o3+$o4+$o5) -join $n;'

SET @psAlterSP = '$p = $d.StoredProcedures[\"$sp\",\"$ss\"]; if($p -eq $null){$p = new-object ($u+''.StoredProcedure'') $d, \"$sp\",\"$ss\";$p.TextHeader=\"CREATE PROCEDURE [$ss].[$sp]$n @drop bit = 0,$n @schema sysname = NULL,$n @name sysname = NULL,$n @indexName sysname=NULL $n AS$n\";$p.TextBody=$o;$p.Create()}else{$p[0].TextBody=$o; $p[0].Alter()}'
SET @psAlterSP=REPLACE(@psAlterSP,'$sp',@sp)
SET @psAlterSP=REPLACE(@psAlterSP,'$ss',@ss)

SET @cmd = 'powershell -Command "'+@psLoadAssemblies+@psGetDatabase+@psGetViews+@psGetFilteredIndexes+@psCompose1+@psCompose2+@psCompose3+@psCompose4++@psCompose5+@psComposeAll+@psAlterSP+'"'
PRINT LEN(@cmd)
DECLARE @result int
INSERT INTO @OUTPUT (line)
exec @result =xp_cmdshell @cmd

IF @result=0 AND (SELECT count(*) FROM @OUTPUT WHERE line is not null)=0
BEGIN
    PRINT 'OK'
END
ELSE
BEGIN
    PRINT 'FAILURE'
    SELECT @script+line FROM @OUTPUT
    WHERE line is not null
    ORDER BY id;
    THROW 50000,'Error during xp_cmdshell execution',1;
END