Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The code is parsed before it is run. When it is parsed SQL Server checks that it can access everything in the code, it cannot access the database that exists on the other server so the parsing step of running the code fails. As a result, you get the error message you've shown.</p> <p>If you want to get around that you can put the code in the IF blocks as dynamically executed code (I always feel this is a bit of a hack/workaround).</p> <pre><code>DECLARE @sql NVARCHAR(4000); if ((select @@servername) = 'ServerA') begin SET @sql = 'use DatabaseA; select top 5 * from dbo.SignUPRequest;' end else if ((select @@servername) = 'ServerB') begin SET @sql = 'use DatabaseB; select top 5 * from dbo.SignUPRequest' end EXEC (@sql) </code></pre> <p>So, what happens here is that you defer the parsing &amp; running of the code that uses the appropriate database for the server to run time, as that what the EXEC statement at the end does.</p> <p><strong>UPDATE</strong></p> <p>Based on the additional comment below you could also rewrite this as:</p> <pre><code>DECLARE @sql NVARCHAR(4000); if ((select @@servername) = 'ServerA') begin select top 5 * from DatabaseA.dbo.SignUPRequest; end else if ((select @@servername) = 'ServerB') begin select top 5 * from DatabaseB.dbo.SignUPRequest; end </code></pre> <p>So, instead of putting in a <code>USE &lt;database-name&gt;</code> at the start, you can also more fully qualify the name of the table in your select statement. If you only have one line of SQL to deal with this could be more effective.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload