使用同義字

適用於:SQL ServerAzure SQL 資料庫 Azure SQL 受控執行個體 Azure Synapse Analytics

同義字是架構範圍物件的替代名稱。 在 SMO 中,同義字是由 Synonym 物件表示。 對象 Synonym 是物件的子系 Database 。 這表示同義字只有在定義同義字的資料庫範圍內才有效。 不過,同義字可以參考另一個資料庫或 SQL Server 遠端實例上的物件。

指定替代名稱的物件稱為基底物件。 物件的 name 屬性 Synonym 是提供給基底物件的替代名稱。

範例

針對下列程式代碼範例,您必須選取程式設計環境、程式設計範本和程式設計語言,才能建立您的應用程式。 如需詳細資訊,請參閱 在Visual Studio .NET 中建立Visual C# SMO 專案。

在 Visual C 中建立同義字#

程式代碼範例示範如何建立架構範圍物件的同義字或替代名稱。 用戶端應用程式可以透過同義字使用基底物件的單一參考,而不是使用多個元件名稱來參考基底物件。

{  
            //Connect to the local, default instance of SQL Server.   
            Server srv = new Server();  
  
            //Reference the AdventureWorks2022 database.   
            Database db = srv.Databases["AdventureWorks2022"];  
  
            //Define a Synonym object variable by supplying the   
            //parent database, name, and schema arguments in the constructor.   
            //The name is also a synonym of the name of the base object.   
            Synonym syn = new Synonym(db, "Shop", "Sales");  
  
            //Specify the base object, which is the object on which   
            //the synonym is based.   
            syn.BaseDatabase = "AdventureWorks2022";  
            syn.BaseSchema = "Sales";  
            syn.BaseObject = "Store";  
            syn.BaseServer = srv.Name;  
  
            //Create the synonym on the instance of SQL Server.   
            syn.Create();  
        }  

在 PowerShell 中建立同義字

程式代碼範例示範如何建立架構範圍物件的同義字或替代名稱。 用戶端應用程式可以透過同義字使用基底物件的單一參考,而不是使用多個元件名稱來參考基底物件。

#Get a server object which corresponds to the default instance  
$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server  
  
#And the database object corresponding to Adventureworks  
$db = $srv.Databases["AdventureWorks2022"]  
  
$syn = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Synonym `  
-argumentlist $db, "Shop", "Sales"  
  
#Specify the base object, which is the object on which the synonym is based.  
$syn.BaseDatabase = "AdventureWorks2022"  
$syn.BaseSchema = "Sales"  
$syn.BaseObject = "Store"  
$syn.BaseServer = $srv.Name  
  
#Create the synonym on the instance of SQL Server.  
$syn.Create()  

另請參閱

CREATE SYNONYM (Transact-SQL)