'EXEC sp_executesql: No cross server join

I'd like to execute following statement with a clause to prevent cross server joins:

SET @Sql = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM ' + QUOTENAME(@Db) + '.bla.Field 
    WHERE Name = @SearchName'

EXEC sp_executesql @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT

For EXEC I use this statement:

  SET @Sql = 'EXEC (''' + REPLACE(@Sql, '''', '''''') + ''')' + CASE WHEN @ServerName = @ThisServer THEN '' ELSE ' AT ' + @ServerName END
    EXEC ( @Sql )

How do I adapt my statement to work with EXEC sp_executesql?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source