使用同义词

同义词是架构范围的对象的替代名称。 在 SMO 中,同义词由 Synonym 对象表示。 对象 Synonym 是对象的 Database 子对象。 这意味着同义词仅在定义同义词的数据库范围内有效。 但是,同义词可以引用另一个数据库或 SQL Server 的远程实例上的对象。

给定可选名称的对象称为基对象。 对象的 name 属性 Synonym 是提供给基对象的替代名称。

示例:

对于以下代码示例,必须选择编程环境、编程模板和编程语言来创建应用程序。 有关详细信息,请参阅 在 Visual Studio .NET 中创建 Visual Basic SMO 项目 ,并在 Visual Studio .NET 中创建 Visual C# SMO 项目

在 Visual Basic 中创建同义词

该代码示例演示如何为架构作用域对象创建同义词或备用名称。 客户端应用程序可以通过同义词对基对象使用单个引用,而不是使用多个部件名称来引用基对象。

在 Visual C 中创建同义词#

该代码示例演示如何为架构作用域对象创建同义词或备用名称。 客户端应用程序可以通过同义词对基对象使用单个引用,而不是使用多个部件名称来引用基对象。

{  
            //Connect to the local, default instance of SQL Server.   
            Server srv = new Server();  
  
            //Reference the AdventureWorks2012 database.   
            Database db = srv.Databases["AdventureWorks2012"];  
  
            //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 = "AdventureWorks2012";  
            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["AdventureWorks2012"]  
  
$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 = "AdventureWorks2012"  
$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)