Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

Deleting old Data from AdventureWorks2012 with powershell

$
0
0

Hi everyone!  I am trying to delete tables from data where the ModifiedDates older than 9 years in AdventureWorks2012 database and i assumed dropping all constraints is a good way to do it. I get console notified that foreign and primary keys are dropped but the delete statement is throwing errors. I am sure that somewhere the key constraints are not getting altered, but i'm not able to figure it out as i'm a relative beginner to T-SQL. The error and code:

The DELETE statement conflicted with the REFERENCE constraint "FK_SalesOrderHeaderSalesReason_SalesReason_SalesReasonID". The conflict
occurred in database "AdventureWorks2012", table "Sales.SalesOrderHeader
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
$option_drop = new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions;
$option_drop.ScriptDrops = $true;

DropScriptingOptions1

$targetDatabaseName = "AdventureWorks2012"
$ServerName="PC-PC"


$server = new-object Microsoft.SqlServer.Management.Smo.Server "PC-PC";
$db = $server.Databases[$targetDatabaseName];

foreach ($table in $db.Tables) {
    foreach ($index in $table.Indexes) {
        if ($index.IndexKeyType -eq "DriPrimaryKey") {
            $index.Script( $option_drop )
        }

    }
        foreach ($Fk in $table.ForeignKeys) {



  $Fk.Script($option_drop)

}

}



foreach ($table in $db.Tables) {

$tablename=$table.Name
$schemaname=$table.Schema
$query = @"
USE AdventureWorks2012

GO

DELETE FROM $schemaname.$tablename WHERE ModifiedDate < DATEADD(YEAR, -9, GETDATE())"@
Invoke-Sqlcmd -Query $query -ServerInstance "$ServerName" -Database $targetDatabaseName

}



Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>