Sql查询结果作为对象的数组PowerShell

时间:2018-04-05 12:46:09

标签: sql powershell

我尝试使用此查询的结果进行操作,然后对结果的特定值运行更新查询。我想要做的是从表中获取所有值,然后检查这些值是否在1到5之间,并将它们变为null。由于我无法在一个更新查询中执行此操作,因此我首先执行select然后对结果中获得的奇异值进行操作,但查询返回{{1}我无法在PowerShell中运行的结果(或者至少我不知道如何)。我能做什么?这个的主要目标应该是更新db上表的所有列,以更改值介于1和5之间的列,并将它们转换为空值 这是代码:

dataset

1 个答案:

答案 0 :(得分:0)

这里有几个月大的新手(我),生病了试试这个!

您实际上可以循环遍历数据集的各行,并访问这些行中的属性(列),修改它,然后动态创建更新语句并在服务器上执行它。

主要部分如下所示,其余部分仅仅是我自己定义的功能。不确定这是不是你的想法,但我的测试设置是这样的。 (注意请在运行下面的代码之前先在powershell会话中执行/定义函数)

 # SET VARIABLES
        $Serv = <Your Server>
        $DB   = <Your DB>
        $TSQL = "SELECT * FROM TestTBL"


# Target Results table from SQL
    $MainResultsTable = (GetSQLData $Serv $DB $TSQL).Tables[0]

#Get Column names
    $Colnames = ($MainResultsTable.Rows | gm -MemberType NoteProperty,Property).Name


# Loop through each row of data from SQL results
    foreach($row in $MainResultsTable.Rows)
    {
        # Construct the TSQL update statement. Using an array to construct the multi column updates.
            $TSQLUpdate = "UPDATE TestTBL SET "
            $TSQLUpdateArr =@()
            foreach($Col in $Colnames)
            {
                # We don't need to update the ID
                    if($Col -ne 'ID')
                    {
                        $TSQLUpdateArr += "$Col = $(EvaluateColumnData $row.$Col)`n" 
                    }
            }
            # join the columns with the corresponding end of TSQL where the target ID is specified
                $TSQLUpdate += $($TSQLUpdateArr -join ",").ToString() + " WHERE ID = $($row.ID);"

            # Execute the update on SQL server
             UpdateSQL $Serv $DB $TSQLUpdate
    }

在这里提供我为SQL编写的函数的几个片段。 [开放优化和评论家使这更快或更''semanticy']

# Define custom user function to set the values to be used for updating
function EvaluateColumnData()
{
    param( $data )

    if($data -le 5){ return "NULL" }
    else { return $data }
}

# Get data from SQL
function GetSQLData()
{
    param( $tgtServ,$tgtDB,$tgtTSQL )
    # Create connection obj
    $SqlConnection                  = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "server="+$tgtServ+";database="+$tgtDB+";trusted_connection=true;"

    # Open SQL connection
    $SqlConnection.open()

    # Create TSQL CMD object and pass the connection object
    $SQLCommand                     = New-Object System.Data.SQLClient.SQLCommand
    $SQLCommand.Connection          = $SqlConnection

    # TSQL statement to be executed
    $SQLCommand.CommandText         = $tgtTSQL
    $SQLCommand.CommandTimeOut      = 0

    # Container/adapter for SQL result
    $resultAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SQLCommand)

    # DataSet where the results are dumped
    $resultDS      = New-Object System.Data.DataSet
    $resultAdapter.Fill($resultDS) | Out-Null
    $SqlConnection.Close()

    return ,$resultDS
}

# Execute TSQL statement without results
function UpdateSQL()
{
    Param( $tgtServ,$tgtDB,$tgtTSQL )
    $ServerConn                  = New-Object System.Data.SQLClient.SQLConnection                               
    $ServerConn.ConnectionString = "server="+$tgtServ+";database="+$tgtDB+";trusted_connection=true;"
    $ServerConn.Open()                               
    $ServerCMD                   = New-Object System.Data.SQLClient.SQLCommand
    $ServerCMD.Connection        = $ServerConn
    $ServerCMD.CommandText       = $tgtTSQL
    $ServerCMD.CommandTimeOut    = 0
    $ServerCMD.ExecuteNonQuery() | out-null
    $ServerConn.Close() 
}

希望这会有所帮助。你可以阅读很多东西(我还在阅读lol),这提供了更好的解释,我建议专注于基础知识。

推荐阅读:DataTables,PS objects/Custom objectshashtable,功能。