Home > Ask the SQL Server Experts > Roman Rehak - SQL Server Development and Reporting Services Questions & Answers > INSTEAD OF trigger to update a SQL Server table
Ask The SQL Server Expert: Questions & Answers
EMAIL THIS

INSTEAD OF trigger to update a SQL Server table

Roman Rehak EXPERT RESPONSE FROM: Roman Rehak

Pose a Question
Other SQL Server Categories
Meet all SQL Server Experts
Become an Expert for this site


Expert advice on database development
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


>
QUESTION POSED ON: 10 December 2007
I would like to create a trigger on insert, update for a table like this:

MyTable (myDate datetime, myTime datetime)

Now, to ease my SQL statements (and performance reason) I want to make sure the column myDate always has the time set to '00:00:00' and the myTime column always has the date set to '1/1/1900.'


>
EXPERT RESPONSE
You can do this in a regular trigger but an "INSTEAD OF" trigger would work even better. It helps avoid dealing with trigger recursion that you would otherwise experience since you will be modifying the underlying table. This type of trigger overrides the action of the statement that triggered it. Instead, it just executes the code inside of the trigger. Here is a sample code that stores the date and time in the format you specified, it creates a table and two INSTEAD OF triggers, one for inserts and the other one for deletes:

CREATE TABLE [dbo] . [MyTable] (
[ID] [int] IDENTITY (1,1) NOT NULL PRIMARY KEY
CLUSTERED,
[myDate] [datetime] NOT NULL,
[myTime] [datetime] NOT NULL,
) ON [PRIMARY]
GO

CREATE TRIGGER dbo.MyTableInsertTrigger ON MyTable
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;

INSERT INTO MyTable
(myDate, myTime)
SELECT CONVERT(VARCHAR(10), myDate, 101),
DATEADD (DD, -CAST (myTime AS FLOAT), myTime)
FROM Inserted
END
GO

CREATE TRIGGER dbo.MyTableUpdateTrigger ON MyTable
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON;

UPDATE MyTable
SET myDate = CONVERT (VARCHAR(10), Inserted.myDate, 101),
myTime = DATEADD (DD, -CAST(Inserted.myTime AS FLOAT),
Inserted.myTime)
FROM Inserted, MyTable
WHERE Inserted.ID = MyTable.ID
END
GO

You can now run these statements and verify that the date and time are stored as you wanted:

INSERT INTO MyTable
SELECT GETDATE (), GETDATE ()

SELECT * FROM MyTable

UPDATE MyTable
SET Mydate = GETDATE (),
myTime = GETDATE ()

SELECT * FROM MyTable

The code that removes the time part from myDate is fairly straightforward – when you convert from datetime to varchar(10), the time part gets truncated. The code that sets the myTime column to '1900/1/1' is more complex. I am using the DATEADD function to subtract number of days between the base date of '1900/1/1' and the numeric value of the datetime in the myDate column. I can do this because internally dates are stored as integers. The numeric value of '1900/1/1' is 0. This code gives you the number of days between today and '1900/1/1':

SELECT DATEDIFF (DD, '1900/1/1', GETDATE () )


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


RELATED CONTENT
SQL/Transact SQL (T-SQL)
Physical data storage in SQL Server 2005 and 2008
SQL Server 2008 data types: Datetime, string, user-defined and more
Enforcing data integrity in a SQL Server database
SQL Server and data manipulation in T-SQL
Supertype and subtype tables in SQL Server
Using SQL Server datetime functions GETDATE, DATENAME and DATEPART
Ordering the results of a SQL query
How to use SQL Server 2008 hierarchyid data type
SQL Server data conversions from date/time values to character types
SQL and SQL Server Tutorial and Reference Guide
SQL/Transact SQL (T-SQL) Research

Roman Rehak - SQL Server Development and Reporting Services
Using BULK INSERT to insert rows from SQL Server dataset to table
SQL Server query to import database names
Troubleshoot SQL Server 2005 SP2 installation error
Workaround to Reporting Services error in SQL Server Express
How can I export stored procedures in SQL Server 2005?
Code to restore SQL Server databases in VB.NET
Stored procedure for a BULK INSERT to SQL Server 2005 text file
BULK INSERT to import data from file to SQL Server database
Retrieve images from SQL Server and store in VB.Net
Can you import Excel data to SQL Server Reporting Services?

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
ACID  (SearchSQLServer.com)
commit  (SearchSQLServer.com)
DAO  (SearchSQLServer.com)
fetch  (SearchSQLServer.com)
OLE DB  (SearchSQLServer.com)
query  (SearchSQLServer.com)
SQL  (SearchSQLServer.com)
T-SQL  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary



Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice

HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Reprints  |  Site Map




All Rights Reserved, Copyright 2005 - 2008, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts