Search code examples
azure-sql-database

Not able to query cross database in Azure SQL


I tried to insert data into another table, in another database, but I get an error:

Reference to database and/or server name in 'xxx.xxx.xxx' is not supported in this version of SQL Server

I'm getting the same error when trying to select from another database.

My SQL code:

INSERT INTO xxx.xxx.xxx 
VALUES (xx,'xx', 'xxxx', xx)

Solution

  • In Azure SQL database Cross database quires are not supported You cannot insert records from one database to another database.

    You cannot use DML statements on Cross database in azure SQL.

    • The only way to insert records is connect to the correct database or switch the database context if you're in SSMS/ADS/ portal Then you can execute your statements.
    • Regarding the cross database quires, you need to use elastic queries like external tables and external data sources suggested by Alberto Morillo

    Sample Code:

    CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'password';
    
    CREATE DATABASE SCOPED CREDENTIAL samplecred2  
    WITH IDENTITY = 'username',  
    SECRET = 'password';
    
    CREATE EXTERNAL DATA SOURCE RemoteReferenceData
       WITH
          (
             TYPE=RDBMS,
             LOCATION='servername.database.windows.net',
             DATABASE_NAME='db name',
             CREDENTIAL= samplecred
          );
    
    CREATE EXTERNAL TABLE [dbo].[tableename]
       (
          Id int,
          Name varchar(20)
       )
       WITH
       (
          DATA_SOURCE = RemoteReferenceData,
          SCHEMA_NAME = 'schemaname',  
          OBJECT_NAME = 'tablename' 
       );
    

    Now you can execute quires on the external table which looks similar.

    Reference -Cross-database Query in Azure SQL Database - Microsoft Community Hub