如何在PowerShell SQL查询中替代变量

时间:2018-12-19 16:04:52

标签: sql function powershell parameter-passing substitution

我需要在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行。

1 个答案:

答案 0 :(得分: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)