Add Computed Columns to store procedure

Product:

Microsoft SQL Azure

Issue:

Want a new column on a table, that is needed only for the SP.

Want two column to be a new one, so we do not need to join on the two columns later.

Suggested Solution:

In a separate query , that you run before your SP,  check if the column exist and if not create it with SQL like this:

IF COL_LENGTH('[Stage].[tablename]','cDate') IS NOT NULL
PRINT 'Column Exists';
ELSE
BEGIN;
ALTER TABLE [Stage].[tablename] ADD cDate AS ( Year + '-' + Month + '-01') PERSISTED;
END;

Or even this will work:

IF COL_LENGTH('[Stage].[tablename]','cDate') IS NULL
BEGIN;
ALTER TABLE [Stage].[tablename] ADD cDate AS ( Year + '-' + Month + '-01') PERSISTED;
END;

You can find out better SQL to this problem.

Should give a new column with data:  2023-09-01, if the Year contain 2023 and Month contain 09.

Then you can compare a date formatted column with your cDate column.

PERSISTED will store the value of the calculation in the table, so it does not need to be calculated when asked for later.

More Information:

https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16 

https://www.sqlshack.com/an-overview-of-computed-columns-in-sql-server/ 

SQL Server Computed Columns

https://database.guide/add-a-computed-column-to-an-existing-table-in-sql-server/ 

https://www.sqlservercentral.com/articles/using-computed-columns 

https://www.tsql.info/ex/sql-check-if-column-exists-in-a-table.php 

https://www.geeksforgeeks.org/how-to-check-if-a-column-exists-in-a-sql-server-table/ 

https://blog.sqlauthority.com/2017/07/29/sql-server-check-column-exists-sql-server-table/ 

https://www.sqlshack.com/sql-if-statement-introduction-and-overview/