【问题标题】:SQL SMO: Find default constraints dependent on functionSQL SMO:查找依赖于函数的默认约束
【发布时间】:2014-07-17 21:54:18
【问题描述】:

下面的脚本改变了函数 [dbo].[RetrieveDefaultValueForColumn1]。但是,由于此函数在两个表(表 1 和表 2)中用作 Column1 的默认值,因此必须暂时删除并重新添加这些默认约束。像这样:

-- drop dependent default constraints
ALTER TABLE [dbo].[Table1] DROP CONSTRAINT [DF_Table1_Column1];
GO

ALTER TABLE [dbo].[Table2] DROP CONSTRAINT [DF_Table2_Column1];
GO

-- alter function
ALTER FUNCTION [dbo].[RetrieveDefaultValueForColumn1] ()
RETURNS SMALLINT
AS
BEGIN
  RETURN 1
END
GO

-- re-add dependent default constraints
ALTER TABLE [dbo].[Table1]
    ADD CONSTRAINT [DF_Table1_Column1] DEFAULT ([dbo].[RetrieveDefaultValueForColumn1]()) FOR [Column1];
GO

ALTER TABLE [dbo].[Table2]
    ADD CONSTRAINT [DF_Table2_Column1] DEFAULT ([dbo].[RetrieveDefaultValueForColumn1]()) FOR [Column1];
GO

如果我要使用 SQL SMO“脚本/依赖项发现”功能以编程方式生成此脚本,如何识别依赖于该函数的所有默认约束?

【问题讨论】:

    标签: sql sql-server sql-server-2008 smo


    【解决方案1】:

    果然。给你,powershell风格。请注意,我对已经存在的文件并不小心。首先在测试环境中运行它以确保您不会破坏任何东西;它对我有用,但这并不意味着它对你有用。无论如何,这个脚本会输出两个 SQL 脚本;一个删除约束,一个创建约束。

    import-module sqlps;
    $s = new-object microsoft.sqlserver.management.smo.server '.';
    $db = $s.databases[ 'adventureworks2012' ];
    
    $drop_options = new-object microsoft.sqlserver.management.smo.scriptingoptions;
    $create_options = new-object microsoft.sqlserver.management.smo.scriptingoptions;
    
    $drop_options.filename = 'c:\temp\default_drops.sql';
    $drop_options.tofileonly = $true;
    $drop_options.scriptdrops = $true;
    $drop_options.AppendToFile = $true;
    
    $create_options.filename = 'c:\temp\default_creates.sql';
    $create_options.tofileonly = $true;
    $create_options.scriptdrops = $false;
    $create_options.AppendToFile = $true;
    
    foreach ( $table in $db.tables ) {
        foreach ( $column in $table.columns ) {
            if ( $column.defaultconstraint.Text -eq '(getdate())' ) {
                $column.defaultconstraint.script( $drop_options );
                $column.defaultconstraint.script( $create_options );
                $column | select parent, name, defaultConstraint;
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多