【问题标题】:How to execute stored procedure from Powershell?如何从 Powershell 执行存储过程?
【发布时间】:2019-05-14 17:49:46
【问题描述】:

希望这不是重复的。我汇总了我在去年左右遇到的许多解决方案,以获得我现在的位置。这对我来说都是相对较新的,我正在寻找最安全和有效的解决方案。当我运行它时,什么也没有发生。预期的结果是执行存储过程。

$Server = 'Server Name'    
$database = 'DBName'
$userName = 'un'
$password = 'pw'
$Name = 'Name'
$Job = '15'
$Logs = Get-Content -Path $global:LOGFILE
$StartTime ='time'
$End = 'End'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "Server=$('$Server');Database=$('$Database');trusted_connection=true;User Id=$('$userName');Password=$('$password')"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText ="EXEC dbo.UpdateOutput @Name,@Job,@StartTime,@End,@Status,@Logs"
$Command.Parameters.AddWithValue("@Name", $Name)| Out-Null
$Command.Parameters.AddWithValue("@Job", $Job)| Out-Null
$Command.Parameters.AddWithValue("@Start", $StartTime)| Out-Null
$Command.Parameters.AddWithValue("@End", $End)| Out-Null
$Command.Parameters.AddWithValue("@Status", $Status)| Out-Null
$Command.Parameters.AddWithValue("@Logs", $Logs)| Out-Null
$Command.ExecuteNonQuery()
$Connection.Close() 

【问题讨论】:

  • 嘿@Brad,这是我写的大部分语法的地方。
  • @robdigm 您确定 SP 不执行吗?您是否在 Profiler 中运行 SQL 跟踪来仔细检查?您可能会花费大量时间来修复脚本中实际上并不存在的问题
  • @Martin 不,我没有。让我研究一下这是怎么做到的。
  • 我运行了跟踪器,它甚至没有命中数据库。

标签: sql-server powershell


【解决方案1】:

像这样去掉 ConnectionString 行中的撇号:

$Connection.ConnectionString = "Server=$($Server);Database=$($Database);trusted_connection=true;User Id=$($userName);Password=$($password)"

【讨论】:

  • 我现在明白了:异常设置“ConnectionString”:“初始化字符串的格式不符合从索引 70 开始的规范。”
  • @robdigm stackoverflow.com/questions/8243008/… 似乎连接字符串与数据库制造商和版本不匹配
  • 我将与我的 DBA 进行验证
  • @robdigm 我唯一可以告诉你的是,连接字符串原样适用于我连接到正在执行通用 sql 的 SQL Server 2014。
  • 我会让 dba 看看脚本并告诉我他的想法,因为它应该可以完美运行。
猜你喜欢
  • 2016-12-03
  • 2016-04-02
  • 1970-01-01
  • 2011-01-08
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 2012-10-01
相关资源
最近更新 更多