我有两个参数from
和to date
。我需要从PowerShell传递到SQL stored procedure。我创建了一个GUI来输入格式为'YYYY-MM-DD'的参数。但是,它是一个字符串,我需要以'YYYY-MM-DD,00:00:000'的格式将其转换为sqldatetime,以便它可以在SQL中正确生成。
我尝试了下面的内容,但它没有用。我做错了什么?
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost;Database=AMSDataWarehouse test;Integrated Security=SSPI"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = "YQBreport1"
SqlParameter param1 = new SqlParameter("@from",System.Data.SqlDbType.DateTime);
param1.Value = $from;
SqlParameter param2 = new SqlParameter("@to",System.Data.SqlDbType.DateTime);
param2.Value = $to;
$SqlConnection.Open()
$sqlcmd.ExecuteNonQuery()
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$SQLResult =$DataSet.Tables[0]
$commands = $SQLResult | foreach-object -process { $_.output }> output.ps1
.\output.ps1
答案 0 :(得分:1)
您的语法无效PowerShell:
SqlParameter param1 = new SqlParameter("@from",System.Data.SqlDbType.DateTime);
param1.Value = $from;
试试这个:
$param1 = $SqlCmd.Parameters.Add("@from", [System.Data.SqlDbType]::DateTime)
$param1.Value = Get-Date $from
$param2 = $SqlCmd.Parameters.Add("@to", [System.Data.SqlDbType]::DateTime)
$param2.Value = Get-Date $to