How do I truncate a table via linked server using a synonym for the table name?

RJ. picture RJ. · Feb 12, 2013 · Viewed 7.4k times · Source

I know I can do the following:

EXEC Server_Name.DBName.sys.sp_executesql N'TRUNCATE TABLE dbo.table_name'

But what if I want to use a synonym for the table?

I'm on SERVER1 and I want to truncate a table on SERVER2 using a synonym for the table name.

Is this possible?

Answer

Jason W picture Jason W · Nov 15, 2016

The link on the correct answer is broken. I ran into a similar problem. My workaround was using the synonyms table to lookup underlying table name, then running a dynamic sql statement. It is documented that synonyms cannot be used with TRUNCATE, but at least this is a decent workaround.

DECLARE @TableName VARCHAR(500) = (SELECT TOP 1 base_object_name
    FROM Server_Name.DBName.sys.synonyms WHERE name = 'table_name')
DECLARE @Sql NVARCHAR(MAX) = 'EXEC Server_Name.DBName.sys.sp_executesql N''TRUNCATE TABLE ' + @TableName + ''''
EXEC sys.sp_executesql @Sql