HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to create a synonym for a column in SQL Server?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
createcolumnsqlsynonymforhowserver

Problem

The following is not working. I want to create a synonym on a column in SQL Server 2017. How would I go about doing this?

CREATE SYNONYM dbo.[ProductTest] for [dbo].[Product].[ProductId]
GO

select ProductTest from dbo.Product

Solution

If you want to retain the table name but refer to an existing column by a new name a computed column will do this for you. The computed value of the column will be just the value of the existing column.

alter table [dbo].[Product]
add [ProductTest] as ([ProductId]);


Now you can write

select
    [ProductId],
    [ProductTest] 
from [dbo].[Product];


The two columns will have the same value, always.

If you reference only the computed column my guess is there won't even be a run-time overhead.

Code Snippets

alter table [dbo].[Product]
add [ProductTest] as ([ProductId]);
select
    [ProductId],
    [ProductTest] 
from [dbo].[Product];

Context

StackExchange Database Administrators Q#227130, answer score: 13

Revisions (0)

No revisions yet.