我正在使用一个SQL Server表,我正在作为数据表进行一些修改并将数据保存回数据库。
我现在被困在为DataTable.Rows.Find(PrimaryKey(找到正确的语法上
为简单起见,我创建了一个包含一些数据的简单数据表 您也可以在自己的终端上对其进行测试。
这是我的语法。
[System.Data.DataTable]$dtGL = New-Object System.Data.DataTable("GL")
#Schemas
$dtGL.Columns.Add("Account", "String") | Out-Null
$dtGL.Columns.Add("Property", "String") | Out-Null
$dtGL.Columns.Add("Date", "DateTime") | Out-Null
$dtGL.Columns.Add("Amount", "Decimal") | Out-Null
[System.Data.DataColumn[]]$KeyColumn = ($dtGL.Columns["Account"],$dtGL.Columns["Property"],$dtGL.Columns["Date"])
$dtGL.PrimaryKey = $KeyColumn
#Records
$dtGL.Rows.Add('00001','1000','1/1/2018','185') | Out-Null
$dtGL.Rows.Add('00001','1000','1/2/2018','486') | Out-Null
$dtGL.Rows.Add('00001','1001','1/1/2018','694') | Out-Null
$dtGL.Rows.Add('00001', '1001', '1/2/2018', '259') | Out-Null
[String[]]$KeyToFind = '00001', '1001', '01/01/2018'
$FoundRows = $dtGL.Rows.Find($KeyToFind)
$FoundRows | Out-GridView
我收到以下错误
Exception calling "Find" with "1" argument(s): "Expecting 3 value(s) for the key being indexed, but received 1 value(s)."
At C:UsersMyUserNameOneDrive - MyUserNameMyCompanyPowerShellSamplesWorking With DataTable.ps1:32 char:5
+ $FoundRows = $dtGL.Rows.Find($KeyToFind)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException
我还尝试分离参数
$P01 = '00001'
$P02 = '1001'
$P03 = '01/01/2018'
$FoundRows = $dtGL.Rows.Find($P01,$P02,$P03)
这是错误
Cannot find an overload for "Find" and the argument count: "3".
+ $FoundRows = $dtGL.Rows.Find($P01,$P02,$P03)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
DataRowCollection.Find 需要一个对象数组。 在编辑之前,您显示您正在传入一个字符串数组。 如果每个主键列都是字符串类型,这将起作用。 由于您有一个日期时间,因此需要传递一个 Object 数组,并且 Date 列的值应为 DateTime 类型。
尝试将 KeyToFind 实现为对象数组的方式更改为对象数组,并在此过程中强制转换每种不同的类型:
[Object[]]$KeyToFind = [String]'00001', [String]'1001', [DateTime]'01/01/2018'
这应该可以很好地工作,我尝试如下:
$P01 = '00001'
$P02 = '1001'
$P03 = '01/01/2018'
$FoundRows = $dtGL.Rows.Find(@($P01,$P02,$P03))