Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change all synonyms to another database

I have production database (for example, PROD1). It has a lot of synonyms to another database (for example, PROD2).

I have created PROD2_TEST (as fully copy of PROD2) and also PROD1_TEST (as full copy of PROD1). But as a result I have PROD1_TEST synonyms to PROD2, instead of PROD2_TEST.

How, can I automatically recreate all synonyms to the test database?

like image 933
renathy Avatar asked Oct 02 '13 08:10

renathy


2 Answers

Based on @artm suggestion I expanded it just a little bit to include parameters to make it more generic. Here is the code

DECLARE @newDB VARCHAR(MAX) = 'newDB',  --newDB to point the synonym to
    @linkedSrv VARCHAR(MAX) = null --if the synonym points to a linked server than specify it here like '[LinkedSrv].' (including the dot in the end)

SELECT  'Drop Synonym [' + SCHEMA_NAME(schema_id) + '].[' + PARSENAME(base_object_name, 1) + '];' AS dropSynonym,
        ' CREATE SYNONYM [' + SCHEMA_NAME(schema_id) + '].[' + UPPER(PARSENAME(base_object_name, 1)) + '] FOR '
        + COALESCE(@linkedSrv, '') + '[' + @newDB + '].[' + COALESCE(PARSENAME(base_object_name, 2),
                                                                     SCHEMA_NAME(SCHEMA_ID())) + '].['
        + UPPER(PARSENAME(base_object_name, 1)) + '];' AS createSynonym
FROM    sys.synonyms`
like image 188
kuklei Avatar answered Sep 19 '22 15:09

kuklei


I've had to do this for the same reasons and this is the query I used. Run the query, copy paste the results to the new server (PROD_Test) and run the produced queries. It handles different schema names and multiple databases in case you're using them:

SELECT 'Drop Synonym [' + SCHEMA_NAME(schema_id) + '].[' + PARSENAME(base_object_name,1) + '];CREATE SYNONYM [' + 
    SCHEMA_NAME(schema_id) + '].[' + PARSENAME(base_object_name,1) + '] FOR [' + COALESCE(PARSENAME(base_object_name,3),DB_NAME(DB_ID())) + '_Test].[' 
    + COALESCE(PARSENAME(base_object_name,2),SCHEMA_NAME(SCHEMA_ID())) + '].[' + PARSENAME(base_object_name,1) + '];'
FROM sys.synonyms
like image 26
artm Avatar answered Sep 18 '22 15:09

artm