Database Scheduled manipulation - c#

I've wrote a Restaurant Management application.
I have a Database based on SQL Server 2005 which has one table named OrdersItems. Every 5 minutes I want to read all rows of this table and based on a specific criteria Update some fields.
I don't want to do that in my main application and I prefer to have an Alternative engine to perform this.
Which method is the best method to perform such task ? Also note that this Table (OrdersItems) is under process every time because main application must be always running and get new Restaurant Orders.

You can create a SQL Server Agent job that does the update every five minutes.
If you are using SQL Server Express edition, you can't use SQL Server Agent because it's only included in the "bigger" versions of SQL Server.
In this case, you can create your jobs manually using batch files and Windows Task Scheduler.

I definitely agree with Christian and dougajmcdonald's points about using SQL Task/ Maintenance. However since you included c# in your tags an alternative is to create a Windows Service.
The benefits of this approach
Can run on a machine that doesn't have the SQL Server Agent installed (including express editions)
Can be run outside the context of a user login.
Has standard stop start pause continue mechanism that's well understood.
If the service itself fails will likely result in an event log
This answer contains a template for a windows service that periodically gets data and executes. You may simply want to change the DoStuff method to execute a stored procedure

Create a dialog timer and let it activate a stored procedure. This has the advantage of being fully contained inside the database (no external process), it does not require SQL Agent (runs on Express) and is completely crash resilient at the point it will survive database detach/attach and backup/restore operations (the scheduled job will run after recovery on the new restored database).

I would expect a SQL Task / Maintenance plan would be the best for this.
You can set them up for whatever interval you want, specifying a SQL statement, maintenance task etc you want to run.
You can also setup alerts etc if you want to know when it fails for example.

Deploy a cron job on a server with access to the database which is started every 5 minutes and processes your data, using transactions. I see one problem there: If the amount of data to be processed is large, it could quite work more than five minutes.

Related

How to automatically delete old records from sql server database?

I'm making a web application in aspnet, and I created a table in the database to insert notifications. I would like to know if there is any way to automatically delete data from this table that is older than 30 days. Is there any way this can be done?
Build a Stored Procedure with T-SQL that remove your older data than 30 days.
Assign procedure to SQL Server Agent.
Run server agent every day at specific hours.
With that way, your procedure will run every day and will delete your older data than 30 days according to the Procedure that you write.
I would like to know if there is any way to automatically
SQL Server build-in tool for schedule tasks (also called jobs) is the SQL Server Agent.
https://learn.microsoft.com/en-us/sql/ssms/agent/sql-server-agent
You can create a JOB which run a DELETE query
Note! I HIGHLY recommend NOT to delete data from the database in most cases! Disk are cheap and you will never know when the history information will be needed, but more important is simply that you should not have a reason for this in most cases. In big system you are using partitions and you can store the old data in separate file as well and there is no need to backup that file every time. In small system you can simply buy another cheap HDD disk if needed. Instead of DELETE rows you should design the system to mark the rows as logically deleted (for example add another column) if needed
Update: and what if we are using SQL Server Express?!?
SQL Server express does not support the use of the SQL Server Agent, which means that we need a different solution to schedule task, and the common solutions you can use are:
Solution 1: Using external scheduler
Disadvantage: This solution is in the Operating System level
If you are using SQL Server on windows, then you can Windows Task Scheduler: start menu -> search for "Task Scheduler" -> Right click "Task Scheduler" and select "Create Basic Task" -> fill the task information -> choose "Start a Program" as the action type and execute a ".bat" file which include sqlcmd command which execute your query
If you are using Linux then you can use Cron daemon - a system-managed executable that runs in memory in the background with which users may schedule tasks.
Solution 2: schedule tasks using SQL Server SERVICE (service broker); CONVERSATION TIMER; MESSAGE; CONTRACT; QUEUE
Note! This is my preferred option and I use it even when Agent is supported for many reasons! Service broker is super reliable, it's part of the SQL Engine, there is almost no overhead, it allows asynchronous and timed (repeated) execution at any time interval. With that said, it does not have access to the operating system like the SQL Agent does.
You can get a full sample including all the code to implement this solution in this post: https://www.sqlteam.com/articles/scheduling-jobs-in-sql-server-express-2

How to run a SQL query automatically on Date basis?

I want to run a timely based query that will run every day at a given time.
How can I do it?
Can it be possible with trigger?
You can use SQL Server Agent job & make schedule to recurring job every day at your desired time.
As per your requirement in SQL Server you should go for SQL Job.
It is fairly simple to set up, create your query as a stored procedure and while configuring your job in step write
EXEC YourStoredProcedureName
You can set a job in SQL Server using SQL server Management Studio. It needs additional rights to view that section in management studio so if not visible you can ask admin guys to give access.
Various database systems have different mechanisms of performing Jobs and in fact both Oracle and SQL Server have jobs that - in easiest scenario - will run a procedure at particular period of time and may be recurring or not.
If you don't have enough access to the SQL Server, you can always explore outside database scenarios. On Windows you have Windows tasks which can periodically run simple console application that could run whatever query you want. On Linux you have CRON that can work similarly. The built-in functionality is - however - preferred.
Yes it is possible. Create cron job for it.
check this: http://blog.bobcravens.com/2009/10/an-event-based-cron-scheduled-job-in-c/

ASP.NET Update database every hour

I want to copy one row from table A to table B per hour on my asp.net website. How can I do that? Do I need win32 application? I would like to avoid that.
This sounds like you want to create a stored procedure and use the Sql Server Jobs scheduler to run it every hour. See here for details of setting that up
Or if you are using Sql Express see this question "How to run a stored procedure every day in SQL Server Express Edition?"
Ideally you wouldn't do this using IIS etc, unless there is some reason you don't have access to the database.
You can use Timer.
If you use SQL Server you can also schedule a job on the DB directly.
I would agree with brodie. Alternativly create a SSIS package and run either as a SQL Job or a scheduled task from command line(using DTEXEC).
http://msdn.microsoft.com/en-us/library/ms365302.aspx - Shows you how to create a basic solution.
http://decipherinfosys.wordpress.com/2008/09/17/scheduling-ssis-packages-with-sql-server-agent/ - Shows you how to schedule your task.
For your exercise either would do the trick. I would suggest using either that you feel more familiar with. But certainly wouldnt suggest creating a timer driven service.
You could create a webpage that accomplishes this and use a free service like pingdom.com to call that page every hour.
EDIT:
Mine is the easy route, probably not the best solution but quick and simple
You can check this out also:
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
see this example for creating a new thread in global asax, http://www.mikesdotnetting.com/Article/129/Simple-task-Scheduling-using-Global.asax
Be aware though if the website goes down the process will not continue to run, if this is a problem a sql batch job or windows service would be better suited, and if the task is resource intensive it would be better to do this on another machine anyway as the global asax method will take away processing resources from your website

Exec Console Application by using TSQL SP?

I have a console application (in C#) to read data from SQL server (Microsoft SQL 2005) and write data to SQL server. What I need right now is to add a trigger to a table to exec the console application when any row of data is changed.
Not sure what SP available on Microsoft SQL server (2005) to launch a console application? and how can I pass the result from app back? Will it be run as sync or asych manor? Is there any permission issue I have to configure?
Don't launch external processes from a trigger, you'll bring the server onto its knees. Doesn't matter if is xp_cmdshell or CLR procedure. Instead use Service Broker and issue a SEND in your trigger to queue a message to a local service and rely on activation to do the external dependent processing, asynchronously and on a separate context.
The xp_cmdshell stored procedure can be used to launch an external process but this is often disabled for security reasons.
As the console application is already written in C#, perhaps it could be re-written as an SQLCLR stored procedure?
This seems a little shaky to me. Is there any chance of the trigger being called frequently, leading to many launches of the application? Also, I don't think the trigger will complete until the console application has finished or failed. Meantime, the operation that caused the trigger to fire will still be waiting.
Does the application need to run right away? If not, then maybe you could run this as a SQL Agent job periodically.
Trigger slow things down and in your case, this will lead to mass chaos. Triggers is not the route you want to take here.
You might want to consider having a console app that polls the database and every time it finds changes, it will display the changed rows for the users consumption.
You can track these changes using a field like [LastUpdatedDateTime] with a default of GetDate(), and don't send this value in your query. Therefore it will always have the latest timestamp of change. You can alternatively, have an audit table that gets filled by a trigger.
I agree with Ken, you might want to think about changing the architecture. Is the console application reading and writing data to the same SQL server that is invoking it? If so you are better off coding that logic into the trigger or stored procedure itself, and/or changing your database schema to make it so your logic doesn't have to be so complicated.

How to run periodic processes on SQL Server 2008

I've built a very simple chatroom-like ASP.NET application which displays current Online/Offline users:
I have a Table with a DateTime column used as a TimeStamp. Every time a user causes a Postback or similar Get event, I update the TimeStamp. I want to, on the server, create a periodic process of some sort that I can use to check how long a user has been inactive given that I know the last time they were active. Once they have been deemed inactive (after a few minutes lets say), I want to set the value of another column to mark them as "Offline".
Any suggestions would be appreciated.
You could create a Sql Server Agent Job that runs periodically.
http://msdn.microsoft.com/en-us/library/ms187910.aspx
http://msdn.microsoft.com/en-us/library/ms186273.aspx
While the answer given above for using SQL Server Agent is a very good solution, have you considered having a component (a WCF component maybe) on the server which is doing all the state management, instead of managing the state in the database directly?
We do something similar by adding a simple webservice to the Asp.Net application, and calling it at a configurable time interval from a windows service running on the same web-server. This allows us to use our business logic, while keeping it all in one place - the web application.

Categories