SQL - how to check table for new data? - sql

I need to create a stored procedure that upon exceution checks if any new rows have been added to a table within the past 12 hours. If not, an warning email must be sent to a recipient.
I have the procedures for sending the email, but the problem is the query itself. I imagine I'd have to make an sql command that uses current date and compares that to the dates in the rows. But I'm a complete beginner in SQL so I can't even use the right words to find anything on google.
Short version:
Using MS SQL Server 2005, how can I check against the dates, then return a result based on whether new rows were created within the last 12 hours, and use that result to decide whether or not to send email?

Something like this should do what you wish.
Select ID
from TableName
where CreatedDate >= dateadd(hour,-12,getDate())
Hope this is clear but please feel free to pose further questions.
Cheers, John

Say your date field in the table is 'CreateDate' and it's of type DateTime.
Your time to compare with is: GETDATE()
(which returns date + time)
To get the datetime value of 12 hours before that, is done using DATEADD:
DATEADD(hour, -12, GETDATE())
so if we want the # of rows added in the last 12 hours, we'll do:
SELECT COUNT(*)
FROM Table
WHERE CreateDate >= DATEADD(hour, -12, GETDATE())
in your proc, you've to store the result of this query into a variable and check if it's > 0, so:
DECLARE #amount int
SELECT #amount=COUNT(*)
FROM Table
WHERE CreateDate >= DATEADD(hour, -12, GETDATE())
and then you'll check the #amount variable if it's > 0.

You could use a trigger, this link has several examples: http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx
USE pubs
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'reminder' AND type = 'TR')
DROP TRIGGER reminder
GO
CREATE TRIGGER reminder
ON titles
FOR INSERT, UPDATE, DELETE
AS
EXEC master..xp_sendmail 'MaryM',
'Don''t forget to print a report for the distributors.'
GO
If you do not want something for each insert/update, you could copy data to a another table then examine that table every 12 hours, report on the rows in it, then delete them...

assuming you have on this table :
- either a unique id autoincrementing
- either a created_timestamp field containing the timestamp of creation of the row
-> have a new table
reported_rows
- report_timestamp
- last_id_seen
(OR)
- last_timestamp_seen
fill the reported row each time you send your email with the actual value
and before sending the email, check with the previous values, so you know what rows have been added

If the table has an identity field, you could also save the max value (as a bookmark) and next time check if there are any rows with an ID greater than your saved bookmark. May be faster if the key is the clustered key.

Related

Delete a record after a period of time automatically in SQL Server?

I have a table which has two attributes: ID & Datetime when that record was created.
How can I make a trigger (procedure?) to delete a record after, say, 1 day?
I want a task which executes itself every X time instead of manually having to do it.
I suggest you to use SQL Server agent and write a stored procedure that deletes every rows that date is passed one day.
You can find how to use Sql server agent jobs here in this link.
And the stored procedure like :
CREATE PROCEDURE DeleteRows()
AS
BEGIN
DELETE FROM mytable
WHERE (DATEDIFF(DAY, DATEADD(day, -1, DateColum), GETDATE())) >= 1
END
Edit :
The number 1 in where statement is days. you can change it to what you want to use.
The statement to delete a record older than one day is:
DELETE FROM tableName WHERE DATEDIFF(day, getdate(), dateColumn) < -1
You would need to cron that statement using whatever language you have available, php for instance.
That said of course it's hard to imagine a scenario where you would want to be deleting records in the first place ;)
You could create a SQL Job to run after one day (or daily as you want.) and execute a specified stored procedure that carries a simple delete statement.
Follow the next topic:-
http://technet.microsoft.com/en-us/library/ms190268.aspx

Can you tell me when data was inserted into a table

I am using MS SQL Server 2008 and I have an sql table with some data that is inserted daily at 6 am by an sql job. The problem I have is that some data has been inserted separately into the job and I need to know when this data was added.
Is there a query I can run that will show me this?
I think the short answer is NO, there's no magic, ad hoc SQL query that will let you go back after the fact and find out when a row was inserted.
If you want to know when a row is inserted, the easiest thing would be to simply add a date or timestamp field with a default value (like getDate()) that automatically fills in the date/time when the row is inserted.
There are, of course, SQL logs available that will let you track when rows are inserted, updated, deleted, etc., but those require set up and maintenance.
Third option would be to have the program that's inserting the data perform some logging.
Add a date field to the table. You can give it a default value of GETDATE()
Then ORDER BY that field.
SELECT Column1, Column2, NewDateColumn
FROM YourTable
ORDER BY NewDateColumn
what i would do is :
/* add new column to keep inserted row date */
ALTER TABLE [schemaName].[tableName] ADD [RecTime] DATETIME;
/* update the existing rows with the current date since there is no way to guess their insertion date */
UPDATE [schemaName].[tableName] SET [RecTime] = GETDATE();
/* and set a constraint to the RecTime column to set current date on every new row added */
ALTER TABLE [schemaName].[tableName] ADD CONSTRAINT [DF_tableName_RecTime] DEFAULT (GETDATE()) FOR [RecTime]
then you can get those rows like :
SELECT *
FROM [schemaName].[tableName]
WHERE NOT(DATEPART(hh, RecTime) = 6 AND DATEPART(mi, RecTime) <= 20)
you can 'play' with '20' if you know how long sql job run
you probably need to look at SQL CREATE TRIGGER to add the logic to know when the data is being added and log that info in another table for further actions. Without further details I am not sure we can say more than that.
As you're referring to data which has already been inserted, the answer is No, unless you already have a datetime column which has a default value of GETDATE(). The best you can manage after the event has occurred is to look at the sequence of rows and determine that it was between two known times.

using UPDATE, SELECTand INSERT INTO statements altogther in MS Access

I have an MS access project in which the tabel of transactions contains as many as 70 records per day. they are common in one parameter, the Date of today.
the normal way to start entering data is to go to teh table and copy records of yesterday then paste them as new records, then changing date from yesterday to today date.
What I need is to use SQL statements to achieve this. I can say that
step 1: use insert into to input the new records in the table.
Step 2: use update statement to change the date.
Step 3: use the select statement to select the records which will have the date to be changed.
How to combine the use of these statements altogther.
thanks
You need something on the lines of:
INSERT INTO Table (Field, Field, Field, ADate)
SELECT Field,Field,Field,Date() As ADate
FROM Table WHERE ADate = Date()-1
Or just change the default value of the date field in the table to Date(), or Now(), and only insert the other fields. Date will then be automatically filled in as today.

How do you choose specific id and time in SQL Server

I have this small program in C# that is constantly sending data to one of my tables (DataTable). The data format is always the same as well as the length.
There are 4 different IDs I am working with here: 2000,2001,2002, ...which are all in a different table. The ID column is the foreign key in my DataTable column.
Initially I thought I could just retrieve the last inserted row in my DataTable for a specific ID. However, I realized that the insert statement does allocate the values into the database in the order they are sent. Therefore, I decided to simply take an ID and get the last row of data based on the timestamp.
I have tried using DatePart but this limits me to only hours. I would want to display a time based on hours and min. ex: 2002 between '4:30:00' and '5:30:00'.
Also, would I have to do a join statement since I would be calling the ID column from another table?
Ive tried this so far: `
use LogDatabase
select * from dbo.DataTable
join CustomerTable
on(Customer_ID = CustIDFk)
where DATEPART(HH, TimeStamp)between 4 and 5 `
The incoming data string looks alot like this:
3-13-2011 3:30:21 2002: 45 Temp:81 Albany NY etc....
I have made columns for the every field of data in my DataTable. As you can see
2002 is the ID which is called Customer_ID in my CustomerTable. I have set this
as my primary key in the CustomerTable and CustIDFk is the foreign key to be linked
with Customer_ID. As you can see, I'm trying to join my Customer table with my Data
table in order to specify the ID. The DATEPART statement allows to give a time range
by either hour or min among others but does not allow a "between 4:30 and 5:30.
Would something like this work?
DECLARE #today DATETIME = CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
SELECT *
FROM dbo.DataTable
WHERE TIMESTAMP BETWEEN DATEADD(mi, 30, DATEADD(hh, 4, #today)) AND DATEADD(hh, 5, #today)

How automatically add 1 year date to an existing date in SQL Server

I have a task to automatically bill all registered patients in PatientsInfo table an Annual Bill of N2,500 base on the DateCreated column.
Certainly I will use a stored procedure to insert these records into the PatientDebit table and create a SQL Job to perform this procedure.
How will I select * patients in PatientsInfo table where DateCreated is now 1 yr old for me to insert into another table PatientDebit.
I have my algorithm like this:
select date of registration for patients from PatientsInfo table
Add 1 year to their DateCreated
Is date added today? if yes,
Insert record into PatientDebit table with the bill of N2,500
If no, do nothing.
Please how do I write the script?
Use DATEADD, i.e.:
SELECT DATEADD(year, 1, '2006-08-30')
Ref.: http://msdn.microsoft.com/en-us/library/ms186819.aspx
Assuming the columns of the 2 tables are the same:
INSERT INTO PatientDebit
SELECT * from PatientsInfo WHERE DateCreated<DATEADD(year, -1, GETDATE())
Make sure you have an index on DateCreated if PatientsInfo has a lot of records as it could potentially be slow otherwise
there should be .add or addyear() function in sql. You add like .add(year, day, month). Read upon sql datetime add year, month and seconds. It is pretty straightforward. It is just like c#.
Dateadd(info). now time is. getdate().