如何从 SSMS 内部使用 Invoke-Sqlcmd?

How to use Invoke-Sqlcmd from inside SSMS?

我 运行 下面的查询(来自 powershell 内部),来自不同的服务器,一切正常:

Invoke-Sqlcmd -Query "
SELECT [ServerName]=@@servername,m.Match_id, m.HostfamilyId, hf.NIEFlag, ra.DS2019Sent 
FROM APIA_Repl_pub.dbo.repl_HostFamily hf 
INNER JOIN APIA_Repl_pub.dbo.repl_Match m ON m.HostfamilyId =  hf.HostFamilyID
INNER JOIN APIA_Repl_Pub.dbo.repl_Aupair ra on ra.AuPairID = m.AupairId
WHERE ra.JunoCore_applicationID = 459630
" -ServerInstance "CTSTGDB"

我什至有时运行将同一个查询放到几台服务器上进行比较,以下面的结果为例:

我只想从 SSMS 中 运行 相同的查询,但看看我做了什么和得到了什么:

(我什至简化了查询,但仍然出现以下错误)

 GO
 declare @sql varchar(8000)
  SET @SQL=N'powershell.exe -command Invoke-Sqlcmd -Query "SELECT [ServerName]=@@servername" -ServerInstance "CTSTGDB"'

IF OBJECT_ID('tempdb..#Radhe','U') IS NOT NULL
   DROP TABLE #RADHE

CREATE TABLE #RADHE(I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, OUTPUT NVARCHAR(4000))

INSERT INTO #RADHE
 EXEC xp_cmdshell @sql

 SELECT * FROM #RADHE

 GO

OUTPUT
Invoke-Sqlcmd : A positional parameter cannot be found that accepts argument 
'[ServerName]=@@servername'.
At line:1 char:1
+ Invoke-Sqlcmd -Query SELECT [ServerName]=@@servername -ServerInstance ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Sqlcmd], ParameterB 
   indingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.SqlServer. 
   Management.PowerShell.GetScriptCommand

 
NULL

我发现了一篇有趣的文章:

6 methods to write PowerShell output to a SQL Server table

它与我的工作方式相关或可以替代。

从 SSMS 内部调用 Sqlcmd 的问题到底是什么?

据我了解,您很难针对与查询所连接的服务器不同的服务器执行查询。好吧,我至少可以想到 2 种在 SSMS 中执行此操作的方法:

  1. 如果您当前的服务器有一个您想要的链接服务器,您可以使用 EXEC statementAT 子句,如下所示:
declare @Sql nvarchar(max) = N'SELECT [ServerName]=@@servername,m.Match_id,
  m.HostfamilyId, hf.NIEFlag, ra.DS2019Sent 
FROM APIA_Repl_pub.dbo.repl_HostFamily hf 
  INNER JOIN APIA_Repl_pub.dbo.repl_Match m ON m.HostfamilyId =  hf.HostFamilyID
  INNER JOIN APIA_Repl_Pub.dbo.repl_Aupair ra on ra.AuPairID = m.AupairId
WHERE ra.JunoCore_applicationID = 459630';

-- This example assumes that the linked server name is the same as the remote server itself
exec (@Sql) at [CTSTGDB];
  1. 如果链接服务器不可用,您可以使用SQLCMD mode查询:
:connect CTSTGDB
go

SELECT [ServerName]=@@servername,m.Match_id, m.HostfamilyId, hf.NIEFlag, ra.DS2019Sent 
FROM APIA_Repl_pub.dbo.repl_HostFamily hf 
INNER JOIN APIA_Repl_pub.dbo.repl_Match m ON m.HostfamilyId =  hf.HostFamilyID
INNER JOIN APIA_Repl_Pub.dbo.repl_Aupair ra on ra.AuPairID = m.AupairId
WHERE ra.JunoCore_applicationID = 459630;
go

:exit
go

可以通过查询 -> SQLCMD 模式菜单选项切换此模式。