Skip to content Skip to sidebar Skip to footer

How Do I Truncate A Table Via Linked Server Using A Synonym For The Table Name?

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 w

Solution 1:

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@TableNameVARCHAR(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

Solution 2:

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;

Post a Comment for "How Do I Truncate A Table Via Linked Server Using A Synonym For The Table Name?"