使用同义词
同义词是架构范围内的对象的另一名称。在 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()