使用Powershell解析SQL数据时遇到问题
我有,我认为,它是一个真正的头部划痕。使用Powershell解析SQL数据时遇到问题
我正在访问数据库以获取帐户列表。每个帐户都有一个account_id和account_parent_id属性(在其他几个属性中)。如果该帐户是另一个帐户的子帐户,则account_parent_id具有父级的帐户ID,如果该帐户是父级(或没有子级),则account_parent_id为空。只有两个级别,所以如果一个帐户有一个或多个孩子,它不会有父母。
我需要的输出是帐户号码(如果该帐户没有子女)以及父母和所有子女(逗号分隔)的帐户号码,如果有子女。这里是我的代码:
$SQLServer = "<database fqdn>"
$SQLDBName = "<databaes name>"
$uid ="<username>"
$pwd = "<password>"
$SqlQuery = "SELECT * from <account table>"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Persist Security Info = True; User ID = $uid; Password = $pwd;"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$data = $DataSet[0].Tables
$SqlConnection.Close()
Foreach ($row in $data) {
Foreach ($account in $row) {
If ($account.parent_account_id -eq $row.account_id) {
$accts += $account.account_id
}
ElseIf ($account.parent_account_id -eq $account.account_id) {
$accts = $account.account_id
}
Return $accts
}
}
的问题是,我没有得到任何东西到$ accts。我在这里错过了什么?
谢谢。
所以,我们确实最终更新了SQL查询。我回来的数据类型是一个DataTable。我拿出一排,并使用如下循环,以获得他需要的数据:
foreach ($item in $tableRow) {
$($item.account_ids)
}
,以达到您想要的效果,最好的办法是做映射SQL:通过Group-Object
和calculated properties
$SqlQuery = @'
SELECT t1.account_id AS parent, t2.account_id AS child
FROM <account table> t1 LEFT OUTER JOIN <account table> t2
ON t1.account_id = t2.parent_account_id
'@
然后你就可以提取您想要的信息:
$data | Group-Object parent |
Select-Object @{n='Parent';e={$_.Name}},
@{n='Children';e={$_.Group.child -join ','}}
如果”再次遇到PowerShell v2或更早版本,您需要用($_.Group | Select-Object -Expand child) -join ','
之类的东西替换$_.Group.child -join ','
。
与该SQL查询,我只得到表中的一行。 “父”列为空白,并且“儿童”列中有一堆帐户名称。 – StackExchangeGuy
对不起,应该是't2.account_id',而不是't2.account_name'。为获得进一步的帮助,您需要显示样本数据。 –
你的命名有些奇怪。 '$ data = $ DataSet [0] .Tables'要么是表格,要么是多个表格。然后执行'Foreach($ data in $ data)' - 是表集合中的这些表,还是表中的行?如果他们是行,你为什么要做'Foreach($行中的$账户){'?无论哪种方式,你如何期待'$ account'和'$ row'都*具有帐户的属性?你为什么在函数外使用'Return'?并且在嵌套循环的内部循环中使用'return' - 将立即退出。你永远不会初始化'$ accts'。 – TessellatingHeckler
您可以直接在SQL中使用类似'select account_id as id,(从account where account_parent_id = id选择group_concat(account_id)')作为子帐号 ,其中account_parent_id为null;' - http://www.sqlfiddle .com /#!9/e02abc/1 – TessellatingHeckler
根据你的查询'$ data'应该包含一个表。当你输出'$ data |时你会得到什么? Format-Table -AutoSize'?另外,我不认为'foreach'循环正在做你认为他们做的事。请显示您的表格结构并解释您想要匹配哪些值与哪些其他值。 –