sql-servert-sqlazure-sql-databasedacpac

Reuse the same set of columns for different tables


I have some .sql files that create SQL Server tables. Some of them have some of their columns in common.

I'd like to create a CommonColumns.sql file which will be imported by the create table .sql files and it will be used for creating these tables.

Is this even possible??

Example - employees.sql:

-- Create the first table
CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    HireDate DATE
);

Managers:

-- Create the second table
CREATE TABLE Managers
(
    ManagerID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    Department NVARCHAR(50)
);

Instead - commonColumns.sql:

DECLARE @CommonColumns {
    EmployeeID INT PRIMARY KEY,
    FirstName NVARCHAR(50),
    LastName NVARCHAR(50),
    Email NVARCHAR(100),
    HireDate DATE
};

employees.sql:

-- Create the first table
-- I know that its not a thing
from commonColumns.sql import CommonColumns
CREATE TABLE Employees
(
    @CommonColumns
);

Managers:

-- Create the second table
-- I know that its not a thing
from commonColumns.sql import CommonColumns
CREATE TABLE Managers
(
    @CommonColumns
);

Same happens with my stored procedures: I have quite some duplicated code and I want to export it in a common file.

The deployment of the database takes place via DevOps pipeline using a .dacpac to Azure SQL instance.

Using :r in sqlcmd is not an option.


Solution

  • In the SQL server there is no built -in the feature to define the re -fitting set of the column for many table definitions. Each creation table command must clearly list all the columns. Although equipment such as SQLCMD supports when using :r command, this method does not match .Dacpac distribution in Azure Devop's pipelines.

    In cases where tables such as employees and managers share common areas such as FirstName, LastName and Email, it is important to raise database design:

    Ultimately, it is important to create a balance between the code repetitive and avoid and maintain a database structure that is clear and manageable. Opponent designs can introduce unnecessary complexity that may not be worth acting.