Invoke-Sqlcmd在SQL中不起作用

时间:2016-06-29 10:46:09

标签: sql invoke-sqlcmd

我在SQL Powershell中使用以下命令生成SQL返回的数据的csv。

- flash.each do |key, value|
              %div{:class => "alert alert-#{key}"}= value


def update
    result = Braintree::Transaction.sale(
        :amount => params[:amount_to_add].to_f,
        # :order_id => "order id",
        :customer_id => customer.customer_cim_id,
        :tax_amount => (params[:amount_to_add].to_f / 11).round(2),
        :options => {
            :submit_for_settlement => true
        }

    )
    if result.success?
      logger.info "Added to #{params[:amount_to_add].to_f} to #{customer.first_name} #{customer.last_name} (#{customer.customer_cim_id})"
      customer.store_credit.add_credit(params[:amount_to_add].to_f)
      redirect_to myaccount_store_credit_path
      # , :notice => "Successfully updated store credit."
    else
      result.errors.each do |error|
        puts error.message
        customer.errors.add(:base, error.message)
        render :show, :notice => error.message
      end
    end
  end

上面的命令在SQL Power Shell中运行得非常好。但是当我尝试使用以下代码从SQL运行时

Invoke-Sqlcmd -Query "myp" -ServerInstance "." | Export-Csv -Path "d:\data\MyDatabaseSizes.csv" -NoTypeInformation

它给出错误

'调用-SQLCMD'不被视为内部或外部命令,

任何人都可以帮我从SQL运行命令。

由于

1 个答案:

答案 0 :(得分:0)

xp_cmdmshell执行Windows shell命令,而不执行PowerShell命令。您当然可以在Windows shell中调用PowerShell,例如:

DECLARE @cmd varchar(1000)
SET @cmd = 'Invoke-Sqlcmd -Query ''myp'' -ServerInstance ''.'' ^| Export-Csv -Path ''d:\data\MyDatabaseSizes.csv'' -NoTypeInformation'
EXEC xp_cmdshell 'powershell.exe -c "' + @cmd + '"'

请注意:

  • 我已将PowerShell命令中的双引号替换为单引号(对于SQL进行转义),因此我可以在Windows命令中使用双引号。如果在PowerShell中需要双引号,最好在文件中使用PowerShell脚本以避免所有这些
  • 您可能还需要更多参数(例如设置执行策略)。 This MSDN page在PowerShell命令行开关方面提供了更多帮助
  • 命令行参数中的管道字符需要使用^
  • 进行转义
相关问题