I run the query below (from inside powershell), from different servers and all is fine:
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"
I even sometimes run the same query into several servers to compare them, see the result below as an example:
I just want to run the same query from inside SSMS, but see what I do and what I get:
(I have even simplified the query but still I get the error below)
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
I found out an interesting article:
6 methods to write PowerShell output to a SQL Server table
It is related or could be an alternative to the way I am working.
what exactly is the problem of Invoke-Sqlcmd from inside SSMS?
As I understand, you struggle with executing a query against a different server than the one the query is connected to. Well, I can think of at least 2 ways of doing this in SSMS:
AT
clause of theEXEC
statement, like this:This mode can be toggled by the Query -> SQLCMD Mode menu option.