Not sure, if this should go on Stack Overflow, or the DBA section.
Having an issue with a procedure I'm writing. I have a variable, lets say:
SET @name sysname --also tried to make as varchar
This is used inside a cursor, and will basically contain SQL Server names. Several of the server names are followed by instances names. For example
DECLARE @name = 'SERVER1\INSTANCE1'
Inside the cursor, I have this query.
SELECT @name, * FROM OPENQUERY(@name,
'SELECT
i.Name,
i.database_id,
b.mirroring_state
FROM msdb.sys.databases i
INNER JOIN msdb.sys.database_mirroring b
ON i.database_id = b.database_id
WHERE b.mirroring_state IS NOT NULL')
which doesn't work because of the \
inside the @name
However, if I try this, it works perfectly.
SELECT 'SERVER1\INSTANCE1', * FROM OPENQUERY([SERVER1\INSTANCE1],
The issue I'm having is trying to use the bracketed identifier with the @name
inside the OPENQUERY.
I have tried several things, including various combinations of OPENQUERY('['+@name+']',
If you just try FROM OPENQUERY([@name],
SQL Server parses it literally as @name.
Any ideas on how to use the servername\instance
name without having these issues?
Edit, full section of the code:
DECLARE @name sysname,
@sql nvarchar(4000)
DECLARE c1 CURSOR FOR
SELECT SUBSTRING (Servername, 2, LEN(Servername)-2)
FROM AllServers
OPEN c1
FETCH NEXT FROM c1
INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql = 'INSERT INTO MirrorResults
SELECT ''[' + @name + ']'', * FROM OPENQUERY([' + @name + '],
''
SELECT
i.Name,
i.database_id,
b.mirroring_state
from msdb.sys.databases i
INNER JOIN msdb.sys.database_mirroring b
ON i.database_id = b.database_id
WHERE b.mirroring_state IS NOT NULL
'')'
EXECUTE sys.sp_executesql @sql;
FETCH NEXT FROM c1
END
CLOSE c1
DEALLOCATE c1