Temporal Table
Temporal Table
Temporal Table
Temporal table is a table that records the period of time when a row is valid.
A period is an interval of time that is defined by two date time columns in a temporal table. A period
contains a begin column and an end column. The begin column indicates the beginning of the period,
and the end column indicates the end of the period. The beginning value of a period is inclusive, but the
ending value of a period is exclusive. For example, if the begin column has a value of '01/01/1995', that
date belongs in the row. Whereas, if the end column has a value of '03/21/1995', that date is not part of
the row.
DB2® supports two types of periods, which are the system period (SYSTEM_TIME) and the application
period (BUSINESS_TIME). The system period consists of a pair of columns with system-maintained values
that indicate the period of time when a row is valid. The begin column contains the timestamp value for
when a row is created. The end column contains the timestamp value for when a row is updated or
deleted.
The system period is meaningful because of system-period data versioning. System-period data
versioning specifies that old rows are archived into another table. The table that contains the current
active rows of a table is called the system-period temporal table. The table that contains the archived
rows is called the history table. You can delete the rows from the history table when those rows are no
longer needed, if you have the correct authorization.
When you define a base table to use system-period data versioning, or when you define system-period
data versioning on an existing table, you must create a history table, specify a name for the history
table, and create a table space to hold that table. You define versioning by issuing the ALTER TABLE ADD
VERSIONING statement with the USE HISTORY TABLE clause.
The application period consists of a pair of columns with application-maintained values that indicate the
period of time when a row is valid. The begin column contains the value for when a row is valid from.
The end column contains the value for when a row stops being valid. A table with only an application
period is called an application-period temporal table. When you use the application period, determine
the need for DB2 to enforce uniqueness across time. You can create a UNIQUE index that is unique over
a period of time.
A bitemporal table is a table that is both a system-period temporal table and an application-period
temporal table. You can use a bitemporal table to keep application period information and system-
based historical information. Therefore, you have a lot of flexibility in how you query data based on
periods of time.
Keywords for flow control in Transact-SQL include BEGIN and END, BREAK, CONTINUE, GOTO, IF
and ELSE, RETURN, WAITFOR, and WHILE.
Example 1:
IF DATEPART (dw, GETDATE()) = 7 OR DATEPART(dw, GETDATE()) = 1
PRINT 'It is the weekend.'
ELSE
PRINT 'It is a weekday.'
Example 2:
DECLARE @i INT
SET @i = 0
WHILE @i < 5
BEGIN
PRINT 'Hello world.'
SET @i = @i + 1
END
Stored Procedure:
If a repetitive T-SQL task has to be executed within an application, then the best repository for it is a
program called a stored procedure, stored in SQL Server. Storing the code inside the SQL Server object
gives us many advantages, like:
You may have executed some ad-hoc queries for tasks like inserting data, querying information in other
systems, or creating new database objects such as tables. All these tasks can be placed within a stored
procedure, so that any developer can run the same code without having to recreate the T-SQL
commands. Also, generalizing the code for all values makes it generic and reusable.
Stored procedures are more than just tools for performing repetitive tasks. There are two main types of
stored procedure – system stored procedures and user-defined stored procedures. We also have
extended stored procedures that can reside as either system or user-defined types. Extended stored
procedures give functionality that is not necessarily contained within SQL Server, like allowing DOS
commands to run and working with e-mail. It is also possible to create your own extended stored
procedures.
END
GO
More details on Integration of an OLE Object with SQL Server will be found at this link.
In SQL Server, many administrative and informational activities can be performed by using system
stored procedures. Every time we add or modify a table, make a backup plan, or perform any other
administrative function from within Enterprise Manager, we actually call a stored procedure specifically
written to complete the desired action. These stored procedures are known as system stored
procedures, which are functions that enhance the basic functionality of SQL Server itself, either by
extending the functionality of an existing system stored procedure or by creating new functionality that
enhances the basics of what is already there.
System stored procedures are prefixed by sp_, so it is not advisable to use sp_ for any of the stored
procedures that we create, unless they form a part of our SQL Server installation. Creating a stored
procedure prefixed with sp_ and placing it in the master database will make it available to any database
without the need to prefix the stored procedure with the name of the database. More details can be
found at this link.
Let's clarify this with an example. If we take the sp_who stored procedure, call it sp_mywho, store it in
the master database, and move to another database such as northwind, we can still execute sp_mywho,
rather than having to specify the procedure in the fully qualified manner as master.dbo.sp_mywho.
A user stored procedure is any program that is stored and compiled within SQL Server (but not in the
master database) and prefixed with sp_. User stored procedures can be categorized into three distinct
types:
SELECT @Mid
END
Many people tend to miss a performance enhancement related to executing or calling a stored
procedure. For example, if you wanted to call the [Ten Most Expensive Products] stored procedure in
the northwind database, you can simply do it as:
You can skip EXEC(UTE), but you will need it if you run one stored procedure within another.
However, this is not the most efficient way to call a stored procedure. When such a command is
processed, SQL Server has a hierarchical method of finding a stored procedure and executing it. First of
all, it will take the login ID of the user who wants to execute the procedure and see if a stored procedure
of that name exists. If it doesn't, then SQL Server will look for the stored procedure under the DBO login.
Hence, always fully qualify your stored procedure with the owner.
Schema
A database schema of a database system is its structure described in a formal language supported by the
database management system (DBMS) and refers to the organization of data as a blueprint of how a
database is constructed (divided into database tables in case of Relational Databases).
Database schema is a way to logically group objects such as tables, views, stored procedures etc.
Think of a schema as a container of objects.
You can assign user login permissions to a single schema so that the user can only access the objects
they are authorized to access.
Schemas can be created and altered in a database, and users can be granted access to a schema. A
schema can be owned by any user, and schema ownership is transferable.
Schema:Database:table::Floor plan:House:room
Trigger:
The SQL CREATE TRIGGER statement provides a way for the database management system to actively
control, monitor, and manage a group of tables whenever an insert, update, or delete operation is
performed. The statements specified in the SQL trigger are executed each time an SQL insert, update, or
delete operation is performed. An SQL trigger may call stored procedures or user-defined functions to
perform additional processing when the trigger is executed.
Unlike stored procedures, an SQL trigger cannot be directly called from an application. Instead, an SQL
trigger is invoked by the database management system on the execution of a triggering insert, update,
or delete operation. The definition of the SQL trigger is stored in the database management system and
is invoked by the database management system, when the SQL table, that the trigger is defined on, is
modified.
An SQL trigger can be created by specifying the CREATE TRIGGER SQL statement. The statements in the
routine-body of the SQL trigger are transformed by SQL into a program (*PGM) object. The program is
created in the schema specified by the trigger name qualifier. The specified trigger is registered in the
SYSTRIGGERS, SYSTRIGDEP, SYSTRIGCOL, and SYSTRIGUPD SQL Catalogs.
What is a Trigger
A trigger is a special kind of a store procedure that executes in response to certain action on the table
like insertion, deletion or updation of data. It is a database object which is bound to a table and is
executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the
required action no the table that they are assigned to.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there
are three types of triggers and hybrids that come from mixing and matching the events and timings that
fire them.
Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this
table, I will be attaching several triggers.
I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into
another audit table. The main purpose of this audit table is to record the changes in the main table.
This can be thought of as a generic audit trigger.
Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to
this table has inserted the record into the Employee_Test_Audit as:-
if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
This disables the After Delete Trigger named trgAfterDelete on the specified table.
BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead
Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a
record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction will
be committed.
Now, let’s try to delete a record with the Emp_Sal >1200 as:-
CONCLUSION
In this article, I took a brief introduction of triggers, explained the various kinds of triggers – After
Triggers and Instead Of Triggers along with their variants and explained how each of them works. I
hope you will get a clear understanding about the Triggers in Sql Server and their usage.