When trouble shouting error’s thrown by T-SQL, naming your primary and foreign keys, proves to be handy.

When creating tables with T-SQL, I use the naming format PK_MyTable_MyColumn1_MyColumn2 and FK_MyTable_MyColumn3_MyColumn4:

if object_id('[dbo].[Address]') is null
begin
    create table [dbo].[Address]
    (
        Id        int not null  identity(1,1) constraint PK_Address_Id primary key
    )
end


if object_id('[dbo].[Person]') is null
begin
  create table [dbo].[Person]
  (
      Id           int not null  identity(1,1) constraint PK_Person_Id primary key,
      AddressId    int not null constraint FK_Person_AddressId foreign key references [dbo].[Address](Id)
  )
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.