【问题标题】:How substitute variable in PowerShell SQL query如何在 PowerShell SQL 查询中替换变量
【发布时间】:2019-05-20 04:01:53
【问题描述】:

我需要在我的 SQL 查询中使用一个变量。这是我的脚本:

function SQLQueryWriteToFile([string]$SQLquery, [string]$extractFile, [string]$facility)
{
   #create sql connection to connect to the sql DB
   $sqlConnection = New-Object System.Data.SqlClient.SqlConnection

   $sqlConnection.ConnectionString = "Server=blah;Database=blah_Test;User ID=blah;Password=blah" 
   $sqlConnection.Open()

   #Create a SqlCommand object to define the query
   $sqlCmd = New-Object System.Data.SqlClient.SqlCommand
   $sqlCmd.CommandText = $SQLquery
   $sqlCmd.Connection = $sqlConnection

   #create a SqlAdapter that actually does the work and manages everything
   $sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
   $sqlAdapter.SelectCommand = $sqlCmd
   $sqlAdapter.SelectCommand.CommandTimeout=300  #set timeout for query execution to 5 minutes (60x5=300)

   #create an empty dataSet for the query to fill with its results
   $dataSet = New-Object System.Data.DataSet

   #execute the query and fill the dataSet (then disconnect)
   $sqlAdapter.Fill($dataSet)
   $sqlConnection.Close()

   #dump the data to csv
   $DataSet.Tables[0] | Export-Csv $extractFile #this may not be comma delimited...need to check

} 

#start here

$SQLquery_Privilege = @"
SELECT *

 FROM "blah_Test".dbo.usr_Person_by_Privileges

WHERE 
       Status in ('Active')  
       and Facility = '$[facility]'
       and Last not like ('%test%')
       and Last not like ('%Test%')

--ORDER BY Last
"@


$extractFiles = @("C:\temp\Privileges_H_Bak.csv","C:\temp\Privileges_E_Bak.csv","C:\temp\Privileges_S_Bak.csv")
$facCode = @("H","E","S")

#Loop through list of files and queries for ProfileLong
for($i=0; $i -lt ($facCode.Length); $i++) {
   SQLQueryWriteToFile $SQLquery_Privilege $extractFiles[$i] $facCode[$i]
}

我使用了调试器,并且传递给函数的查询确实在其中显示了 $facility 变量而无需替换。如何让它进行变量替换?此外,传递给函数的 $facility 有一个值。

每个提取文件中显示 0 个结果。当我在查询中单独包含每个 H、E、S 并运行脚本时,它会返回大量行。

我尝试查看substitute variable powershell sql,但我可以说我的查询仍然返回 0 行,即使我认为我正在做他们所做的事情。

【问题讨论】:

    标签: sql function powershell parameter-passing substitution


    【解决方案1】:

    使用query parameters 代替字符串替换(这也可以防止 SQL 注入向量):

    $SQLquery_Privilege = @"
    SELECT *
    
    FROM "blah_Test".dbo.usr_Person_by_Privileges
    
    WHERE 
           Status in ('Active')  
           and Facility = @facility
           and Last not like ('%test%')
           and Last not like ('%Test%')
    
    --ORDER BY Last
    "@
    
    # inside SQLQueryWriteToFile
    $sqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $sqlCmd.CommandText = $SQLquery_Privilege
    $sqlCmd.Parameters.Add('@facility',$facility)
    

    【讨论】:

    • 非常感谢!这非常有效。并感谢您指出它可以防止 SQL 注入!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多