How to create an alias of database in SQL Server

前端 未结 7 1083
鱼传尺愫
鱼传尺愫 2020-12-09 15:12

We have a very old software has been created around 10 years ago and we don\'t have source code.

The software uses two databases, DB01 and DB02

7条回答
  •  有刺的猬
    2020-12-09 15:53

    I found Charles' answer (and the linked workaround in the comment by maxcastaneda) very useful. I followed this approach and it works for me. I have streamlined it a bit and created the following query that brings up all required synonyms to create.

    As a prerequisite for this snippet both the original DB and the synonym/alias db have to be on the same server otherwise in case you use linked server or so you have to modify it a bit. It should be fairly easy to put this into a small sp to update the synonyms automatically.

    USE 
    SELECT 
    '[' + TABLE_NAME + ']', 
    '[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']',
    'IF EXISTS (SELECT * FROM sys.synonyms WHERE name = ''' + TABLE_NAME + ''') DROP SYNONYM ['+ TABLE_NAME + '];   CREATE SYNONYM [' + TABLE_NAME + '] FOR .' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']' AS SynonymUpdateScript FROM .INFORMATION_SCHEMA.TABLES
    

    Don't forget to enter you Db names at the <...> spots.

    Just copy the content of the SynonymUpdateScript Column and execute it in the synonym DB - or create a stored procedure for this task.

    Be aware there is an issue if you have views in place that refer to tables or other db objects without the 2 part naming convention. Those synonyms won't work. You should fix this in the original objects / views.

提交回复
热议问题