Share via

Sync two table column names

Madhusudan Reddy Mandala 1 Reputation point
2021-08-17T12:21:17.393+00:00

Create a Stored Procedure for Sync two Column names(Field names) of those tables
For Example I have two tables(A and B) .
if i Change a column in table A and Executed that Stored procedure then it will B table Column name change.

SQL Server Reporting Services
SQL Server Reporting Services

A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

1 answer

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2021-08-17T15:13:56.533+00:00

    Check this procedure:

    create or alter procedure SyncAB
    as
    begin
        declare @oldname varchar(max) = 
            (
                select [name]
                from sys.columns
                where object_id = object_id('B')
                except 
                select [name]
                from sys.columns
                where object_id = object_id('A')
            )
    
        declare @newname varchar(max) = 
            (
                select [name]
                from sys.columns
                where object_id = object_id('A')
                except 
                select [name]
                from sys.columns
                where object_id = object_id('B')
            )
    
        declare @sql varchar(max) = concat('sp_rename ''B.', quotename(replace(@oldname, '''', '''''')), ''', ', quotename(@newname, ''''), ', ''COLUMN''')
    
        --print @sql
    
        exec (@sql)
    end
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.