Search code examples
sqllinked-serverlocaldb

Localdb linked servers


I'm trying to replicate a production environment locally and the production database uses a linked server. I've been able to create multiple instances of localdb; is it possible to create a linkedserver between localdb instances? If not, what other options do I have available (ideally without having to use a full sql instance).


Solution

  • Not sure if it's bad form to answer your own question but in case anyone else has the same issue in the future, it turns out it is possible and pretty straight forward. Once you've created your new instance of localdb, use this:

    USE master
    
    IF EXISTS(SELECT * from sys.servers WHERE name = N'{serverName}')
    BEGIN
        DECLARE @serverId INT
        SELECT @serverId = server_id FROM sys.servers WHERE name = N'{serverName}'
        IF EXISTS(SELECT * FROM sys.linked_logins WHERE server_id = @serverId)
        BEGIN
            EXEC sp_droplinkedsrvlogin '{serverName}', null
        END
    
        EXEC sp_dropserver '{serverName}'
    END
    
    EXEC sp_addlinkedserver     
       @server=N'{serverName}',   
       @provider=N'SQLNCLI',   
       @srvproduct=N'',
       @datasrc=N'{dataSource}';  
    EXEC sp_addlinkedsrvlogin
        @rmtsrvname=N'{serverName}',
        @useself='true'