使用DBATOOLS

问题描述

我有这段代码用Excel工作表中的值更新表中的几列。我尝试使用sqlserver模块来实现此目的,但我想知道是否可以使用DBATOOLS模块来执行操作?

for ($row8 = 9; $row8 -lt 40; $row8++) {
    if ([string]::IsNullOrEmpty($ws3.Cells.Item($row8,3).Value2)){break} else {
        $sqlCmd.CommandText = "UPDATE $Table7 SET STCW_Cert_Held = $ws3.Cells.Item($row8,18).Value2,ISPS = $ws3.Cells.Item($row8,19).Value2,Marine_Medical_Exp = $ws3.Cells.Item($row8,20).Value2,Petronas_Medical_Exp = $ws3.Cells.Item($row8,21).Value2,OSP_Exp = $ws3.Cells.Item($row8,22).Value2,Shell_SafetyPassport_Exp = $ws3.Cells.Item($row8,23).Value2,Boseit_Exp = $ws3.Cells.Item($row8,24).Value2,BT_STCW_Exp = $ws3.Cells.Item($row8,25).Value2,Rigging_Slinging_Exp = $ws3.Cells.Item($row8,26).Value2,FoodHandling_Exp = $ws3.Cells.Item($row8,27).Value2,H2S_Exp = $ws3.Cells.Item($row8,28).Value2,COC_Exp = $ws3.Cells.Item($row8,29).Value2,COR_Exp = $ws3.Cells.Item($row8,30).Value2,Seaman_Card_Exp = [string] $ws3.Cells.Item($row8,31).Value2,Passport_Exp = [string] $ws3.Cells.Item($row8,32).Value2 WHERE PasportNumber =  $ws3.Cells.Item($row8,3).Value2"

    }
}

解决方法

可以使用Invoke-DbaQuery完成表的更新。与其将Excel中的数据链接到单个语句中,不如使用参数化查询。也就是说,创建一个varialbes集合并将其作为查询参数传递。请参阅文档的示例5。这使代码更易于阅读,也可以保护您免受SQL注入的侵害。像这样

$query = 'UPDATE $Table7 SET STCW_Cert_Held = @STCW_Cert_Held,ISPS = @ISPS,...  where PasportNumber = @PasportNumber'

for ($row8 = 9; $row8 -lt 40; $row8++) {
    if ([string]::IsNullOrEmpty($ws3.Cells.Item($row8,3).Value2)){break} else {

        # Build the parameter set
        $params = @{
            STCW_Cert_Held = $ws3.Cells.Item($row8,18).Value2  # Description
            ISPS = $ws3.Cells.Item($row8,19).Value2    
            # ... omitted lots of parameters
            PasportNumber =  $ws3.Cells.Item($row8,3).Value2   # Other notes
        }

        Invoke-DbaQuery -SqlInstance . -Query $query -SqlParameters $params
    }
}

在使用时,请更改变量名称,并避免使用幻数。截至目前,$row8 –这甚至意味着什么?您从第8行开始阅读,对不对?当Excel源发生更改时-他们总是这样做-$row8没有任何意义。另外,您从哪里获得40的上限?您应该有一个带有清晰名称的常量。像这样

# Skip 7 rows of headers
$startRow = 8 
# Explain why there will not be more than 40 rows
$lastRow = 40 
# Even better,use a function that finds out how 
$lastRow = Get-LastRow($myExcelFile) much to import.

for ($row = $startRow; $ro8 -lt $lastRow; $row++) {
    ...
}