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.
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:
Generalization: When many tables have similar columns, it may indicate that they are special versions of a wide device. For example, employees and managers can be regarded as the role of a more ordinary person unit. In this case, you can create a single person table to contain shared properties, with several tables referred to to store role-specific data with multiple tables. It reduces the profits and improves data integrity.
CODE GENERATION Tools: If there are concerns about standardization and repetition, the use of the code production tool can help. These devices continuously streamline the process of creating the SQL script, reducing manual work and reducing the possibility of errors.
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.