如何避免在SQL同义词创建中硬编码DB名称

时间:2015-05-04 14:16:31

标签: sql sql-server stored-procedures synonym

使用SQL Server 2008 R2。我有一个充满以下声明的脚本:

create synonym [synonym_name] for [linkedServerName].[databaseName].[ext].[tableName1]
create synonym [synonym_name] for [linkedServerName].[databaseName].[ext].[tableName2]

问题: 1.有没有办法避免4部分命名。特别是硬编码的DB名称

  1. LinkedServer创建的现有脚本。这可以在创建同义词时使用吗?

  2. 为多个表/视图创建同义词的最佳方法是什么?

    declare @Server sysname,
    @db sysname,
    @Schema sysname,
    @Table sysname,
    @statement varchar(max)
    
    SELECT @Server = 'Venice',
    @db = 'venice1', 
    @Schema = 'ext'
    
    EXEC('CREATE SYNONYM synonym_name1  FOR '+ @Server +'.'+ @db +'.' + @Schema  + '.Table1')
    EXEC('CREATE SYNONYM synonym_name2  FOR '+ @Server +'.'+ @db +'.' + @Schema  + '.Table2') 
    
  3. 思考:这是唯一的方法吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

declare @Server sysname,
        @db sysname,
        @Schema sysname,
        @Table sysname,
        @statement varchar(max)

SELECT @Server = 'ServerName',
       @db = 'DatabaseName',
       @Schema = 'SchemaName',
       @Table = 'TableName'

set @statement = 'CREATE SYNONYM synonym_Name  FOR '+
                  @Server +'.'+ 
                  @db +'.' + 
                  @Schema  + '.' + 
                  @Table 

EXEC (@statement)

答案 1 :(得分:0)

是的,这是唯一的方法。每MSDN documentation Synonym -- SQL Server Syntax CREATE SYNONYM [ schema_name_1. ] synonym_name FOR <object> <object> :: = { [ server_name.[ database_name ] . [ schema_name_2 ]. object_name } 创建语法需要DB名称,如下所示,除非您正在学习动态SQL。

         <select kendo-drop-down-list
                k-options="DropDownOptionsTest"></select>