共用方式為


使用同義字

同義字是結構描述範圍物件的替代名稱。在 SMO 中,同義字是由 Synonym 物件表示。Synonym 物件是 Database 物件的子系。這表示同義字只有在其定義所在的資料庫範圍內才有效。不過,同義字可以參考另一個資料庫或 SQL Server 遠端執行個體上的物件。

已具有給定替代名稱的物件也稱為基底物件。Synonym 物件的名稱屬性是為基底物件所提供的替代名稱。

範例

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

在 Visual Basic 中建立同義字

此程式碼範例示範如何為結構描述範圍物件建立同義字或替代名稱。用戶端應用程式可以透過同義字使用單一參考來參考基底物件,而不是使用多重部分名稱來參考基底物件。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server()
'Reference the AdventureWorks2008R2 database.
Dim db As Database
db = srv.Databases("AdventureWorks2008R2")
'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.
Dim syn As Synonym
syn = New Synonym(db, "Shop", "Sales")
'Specify the base object, which is the object on which the synonym is based.
syn.BaseDatabase = "AdventureWorks2008R2"
syn.BaseSchema = "Sales"
syn.BaseObject = "Store"
syn.BaseServer = srv.Name
'Create the synonym on the instance of SQL Server.
syn.Create()

在 Visual C# 中建立同義字

此程式碼範例示範如何為結構描述範圍物件建立同義字或替代名稱。用戶端應用程式可以透過同義字使用單一參考來參考基底物件,而不是使用多重部分名稱來參考基底物件。

{
            //Connect to the local, default instance of SQL Server. 
            Server srv = new Server();

            //Reference the AdventureWorks2008R2 database. 
            Database db = srv.Databases["AdventureWorks2008R2"];

            //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 = "AdventureWorks2008R2";
            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["AdventureWorks2008R2"]

$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 = "AdventureWorks2008R2"
$syn.BaseSchema = "Sales"
$syn.BaseObject = "Store"
$syn.BaseServer = $srv.Name

#Create the synonym on the instance of SQL Server.
$syn.Create()