我有一個Powershell函數用於在SQL中運行多個查詢並導出爲CSV。每個查詢都依賴於一個日期變量。有沒有辦法使用我當前的設置將這個日期變量從Powershell傳遞到這些SQL腳本(不是存儲過程)?任何幫助深表感謝!將一個變量從Powershell傳遞到保存的SQL腳本
Function Run-Query
{
param([string[]]$queries,[string[]]$sheetnames)
Begin
{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; User ID = $uid; Password = $pwd;"
Write-host "Connection to database successful."
}#End Begin
Process
{
# Loop through each query
For($i = 0; $i -lt $queries.count; $i++)
{
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
# Use the current index ($i) to get the query
$SqlCmd.CommandText = $queries[$i]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
# Use the current index ($i) to get the sheetname for the CSV
$DataSet.Tables[0] #| Export-Csv -NoTypeInformation -Path "C:\Users\mbaron\Downloads\$($sheetnames[$i]).csv"
}
}#End Process
End
{
$SqlConnection.Close()
}
}#End function run-query.
你在哪裏查詢來自哪裏更換?此功能不會生成或編輯查詢? – Matt
閱讀使用ADO.NET進行參數化查詢 – alroc
@Matt我從計算機上的文件中提取查詢 $ SqlQuery1 = get-content「C:\ Documents \ SQL Server Management Studio \ test \ test.sql」輸出字符串; $ queries = @() $ queries + = @「 $ SqlQuery1 」@ – mtb2434