When a record is inserted in sql server - sql-server

I got a task to do, but I don't know exactly how to do it.
I need a Stored Procedure to run every 5 min and validate if a new record has been inserted in one table. If new record is found then execute an insert into another table to make a copy of that record, but if not, then nothing happens and both tables remain the same.
In other words, I need something similar to "after insert" trigger, but I don't want to use a trigger.

Create the stored procedure that you want to run, and then install it as a scheduled job within sql server that runs every 5 minutes.

Do what jhilden suggests with the SQL job running every 5 minutes.
The SP needs to look at the latest record in the copy of the table (timestamp or MAX(ID) if you are conserving the IDs accross the two tables) then check if there is/are a record(s) in the original table with a higher timestamp (or ID), if so copy it/them accross.

Related

Is there a way to set up SQL Server to automatically delete some rows on certain condition

Is there a way to set up SQL Server to automatically delete some rows based on certain conditions?
For example I have a table TblNote with a column createDate to store date that row was created, and a column deleteDate to store date so that this row will be deleted when deleteDate matches current date.
How can I set up server to do that?
You could probably use SQL jobs that will run on daily basis at a certain time, pick those records which have delete-date less than or equal to current date and will perform delete operation on those records.
You can see this link to learn how to schedule sql jobs.
Yes there is :
Add a trigger for column insert or update. However this will work only if a record DMQ takes place.
or
create a procedure that checks it and place it in a job monitor(if you have licensed SQL server) or Task scheduler.

Sql Server rows being auto inserted without a trigger

I have a table in sql server, for which, if I delete a row from it, a new row is inserted with the same data, and userid as the one I deleted. There are no triggers on this table. In addition, I did a search of all database objects that reference this table, and there are no triggers anywhere in the database that reference this table, only some stored procedures, none of which have any code that would cause this behavior.
To be clear, if I run this query:
delete from my_table where id = 1
the row with the id of 1 will be deleted, but a new row will be inserted that has the same userid, and date as the deleted row. No application code involved, just a straight sql delete statement run directly on the database causes this.
What else besides a trigger could be causing this to happen? I've never encountered something like this before.
It took me a long time, but I discovered this was being caused by a "rogue" linq-to-sql dll that was running in spite of it's parent app being killed.
The good news is, there isn't some weird non-trigger way to insert rows on delete in SQL, so we can all resume our normal lives now, knowing all is as it was.

SQL Server - Automatically Calculate total every day

I need to keep a daily statistic of the count of records in a table.
Is there a way to automate counting the records daily and writing the result into another table? Maybe using a SQL Agent Job or something like that?
I'm using SQL Server 2008.
Thank you!
Edit:
If I delete today all records from 1/1/2010, the statistic still needs to show that at 1/1/2010 there were 500 records at the end of the day. So solely using GetDate() and summing up doesn't work, as I'd get 0 records with that method for 1/1/2010.
Add a column to your table like so:
ALTER TABLE My_Table
ADD insert_date DATETIME NOT NULL DEFAULT GETDATE()
You can then query against that as SQL intended.
Insert trigger: update counting table record for today (insert if not already created)
Delete trigger: decrement counting table record for today (insert if not already created)
In my opinion you answered your own question with the best option. Create a Job that just calls a stored procedure getting the count and stamping them.
The other option mentioned by Tom H. is a better choice, but If you can't alter the table for whatever reason the job is a good option.
Another option could be to place an insert trigger on that table to increment a count somewhere, but that could affect performance depending on how you implement it.
Setting up the job is simple through the SQL Management studio interface with a schedule of how often to run and what stored procedure to call. You can even just write the command directly in the command window of the step instead of calling a sp.
Tom's answer with OMG_Ponies' addendum about tombstoning instead of deleting is the best answer. If you are concerned about how many records were in the table on a certain day, there is a good possibility that someone one day will ask for information about those records on that day.
If that is a no go, then as others have said, create a second table with a field for the PK of the last record for the day, and then count for the day, then create a job that runs at the end of each day and counts all records with OrginalTable.PK > MAX(NewCountTable.Last_PK_Field) and adds that row (Last_PK_Field, Count) to the NewCountTable.
SQL Job is good -- yes.
Or you could add a date column to the table defaulted to GETDATE(). This wouldn't work if you don't want your daily counts to be affected by folks deleting records after the fact.

Monitoring a calculated data (A person's age) in SQL Server

I have a table, tblClient, which stored a client's date of birth in a field of type datetime, DOB.
The goal here is that, when a client reaches 65 years old (need to be calculated thru DOB), I need to insert a new record into another table.
But since the age of a client does not change due to a database transaction (INSERT,UPDATE,DELETE), trigger is out of question.
What would be a good idea to montior such changes?
create a sql agent job that runs daily or hourly that will do this calculation with T-SQL and then if someone reaches 65 it will do the insert
Keep it as self-contained to SQL Server as possible - a SQL Server Agent job that periodically executes a stored procedure should do nicely.
A scheduled task or SQL Server maintenance plan that runs a stored procedure as often as required, updating the required rows.
What about a nightly job using SSIS with a stored procedure that checks and if it happens that they are 65 it enters a new row in the table?
you can create a SQL Server Agent Job within the database using SQL Server Management Studio for this:
http://www.databasedesign-resource.com/sql-server-jobs.html
Set up a daily job to EXEC BirthdayProcessingProcedure or whatever you want to name it.
As long as the database is up and running, the JOB will run according to the schedule you set up (from within the database).
I'm going to propose another approach - run something every time a DOB is updated (or added) that calculates the period from now until the first person reaches 65. Then (re-)schedule a job to run at that time.
Also, I can't believe you need to insert that row the second they reach 65, so a once-a-day procedure that calculates today's new 65year olds would seem good enough?
How about a new field that is age65 date. Calculate it once on record insert, then you can query to your hearts content on this field. You will need to do this is a trigger (and account for updates, they are rare for DOB fields but possible when they are mistyped.) Now that I think about it some, a calculted filed will probably work instead of a trigger.
Then run a daily job to catch anyone who turned 65 since the last time the job was run successfully. Make sure to handle this so that if the job fails one day, the people from that daty are picked up the next run.
The reason why I suggest this is that calculating the age of every person inyour database every day is such a waste of resources for a calculation that really only needs to be done once. Ok not a big deal when you have 100 people, big problem when you have a million. Doindthis kindof calc on a million records to identify the three you need is painful. Doing it once on data entry, not so bad.

After insert trigger - SQL Server 2008

I have data coming in from datastage that is being put in our SQL Server 2008 database in a table: stg_table_outside_data. The ourside source is putting the data into that table every morning. I want to move the data from stg_table_outside_data to table_outside_data where I keep multiple days worth of data.
I created a stored procedure that inserts the data from stg_table_outside_Data into table_outside_data and then truncates stg_table_outside_Data. The outside datastage process is outside of my control, so I have to do this all within SQL Server 2008. I had originally planned on using a simple after insert statement, but datastage is doing a commit after every 100,000 rows. The trigger would run after the first commit and cause a deadlock error to come up for the datastage process.
Is there a way to set up an after insert to wait 30 minutes then make sure there wasn't a new commit within that time frame? Is there a better solution to my problem? The goal is to get the data out of the staging table and into the working table without duplications and then truncate the staging table for the next morning's load.
I appreciate your time and help.
One way you could do this is take advantage of the new MERGE statement in SQL Server 2008 (see the MSDN docs and this blog post) and just schedule that as a SQL job every 30 minutes or so.
The MERGE statement allows you to easily just define operations (INSERT, UPDATE, DELETE, or nothing at all) depending on whether the source data (your staging table) and the target data (your "real" table) match on some criteria, or not.
So in your case, it would be something like:
MERGE table_outside_data AS target
USING stg_table_outside_data AS source
ON (target.ProductID = source.ProductID) -- whatever join makes sense for you
WHEN NOT MATCHED THEN
INSERT VALUES(.......)
WHEN MATCHED THEN
-- do nothing
You shouldn't be using a trigger to do this, you should use a scheduled job.
maybe building a procedure that moves all data from stg_table_outside_Data to table_outside_data once a day, or by using job scheduler.
Do a row count on the trigger, if the count is less than 100,000 do nothing. Otherwise, run your process.

Resources