如何使用 PowerShell 在 SQL 服务器中仅插入唯一记录

How to insert only unique record in SQL Server using PowerShell

我正在使用 PowerShell 将我的 CSV 数据插入我的 sql 服务器数据库,但我只是想知道如何修改我的 sql 查询,以便它检查 GID 和源值已在 Daily_Proc table 中匹配,如果不存在则仅插入。

基本上我不想每次 运行 脚本时都在我的数据库中一次又一次地插入相同的记录。

Function InsertError {
    $ErrorActionPreference = 'Stop'

    # check for file explicitly (in case a directory with that name exists)
    if (![System.IO.File]::Exists($Global:ErrorReport)) {
        # throwing an exception will abort the job
        write-log "Exiting script, no file found"
        throw (New-Object System.IO.FileNotFoundException("File not found: $Global:ErrorReport", $Global:ErrorReport))
    }
    else {
        $CSVImport = Import-CSV $Global:ErrorReport
        ForEach ($CSVLine1 in $CSVImport) {
            $CSVHold1 = $CSVLine1.Hold
            $CSVGID1 = $CSVLine1.GID
            $CSVSource1 = $CSVLine1.Source
            $CSVTYPE1 = $CSVLine1.TYPE
            $CSVMessage1 = $CSVLine1.Message
            $CSVCreatedDate1 = $CSVLine1.Time

            If ($CSVMessage1 -ne "The mailbox or SharePoint site may not exist.  If this is incorrect, please contact Microsoft support.  Otherwise, please remove it from this policy.") {
                $query = "USE $Global:Database
            INSERT INTO Daily_Proc (Hold, GID, Source, Type, CreatedDate, Status)
            VALUES('$CSVHold1', '$CSVGID1', '$($CSVSource1 -replace "'","''")','$CSVTYPE1', '$CSVCreatedDate1','Error-Retry');"

                Invoke-Sqlcmd -Query $query -ServerInstance $Global:Server -Database $Global:Database
            }
        }
    }
}

所以我相信你应该能够像下面那样做:

INSERT INTO Daily_Proc (Hold, GMID, Source, Type, CreatedDate, Status)
SELECT '$CSVHold1', '$CSVGMID1', '$($CSVSource1 -replace "'","''")','$CSVTYPE1', '$CSVCreatedDate1','Error-Retry'
WHERE NOT EXISTS (SELECT 1
                  FROM Daily_Proc
                  WHERE Hold = '$CSVHold1'
                  AND GMID = '$CSVGMID1'
                  AND Source = '$($CSVSource1 -replace "'","''")'
                  AND Type = '$CSVTYPE1'
                  AND CreatedDate = '$CSVCreatedDate1'
                  AND Status = 'Error-Retry')

插入....select 不存在的技术总是能很好地防止欺骗和 pk 违规。