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?
According to this blog post you cannot, but he provides a work around.
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
Create a Stored Procedure in Server2 Database for Truncate Tables then call the Stored Procedure from Server1.
Like this :-
EXEC [Server2].[DBName].[SchemaName].sp_TruncateTable;