I am using synonym in stored procedure (SP) to run select on the linked databases. The database name is calculated based on the input of the SP. The SP works fine most of the time, but if the same SP is called multiple times via a program, I get error as -
Invalid Object Name Synonym_Name
Restarting the application fixed the error - but this being triggered via a service call, it's not acceptable.
In starting of the SP, I have already taken care of checking if the object exists, and if yes drop it, then create it -
IF EXISTS(select * from sys.synonyms s where name = 'Synonym_Name' )
BEGIN
DROP SYNONYM [dbo].[Synonym_Name]
END
EXEC ('CREATE SYNONYM [dbo].[Synonym_Name] FOR ' + @DB + '.[dbo].[TableName]')
How can I avoid this Invalid Object name error?
From what I read on all the forums, there is no specific ID and synonym can be deleted by anybody. Is there any other way of handling the situation as the table name is later referred at multiple locations - for inserting from select from the table, variable assignment etc.
I am not sure if this question is already covered - I did search and was not able to find any.