Executing SQL Query after particular point iof Time - sql

In our project we have requirement that, after receiving sms message from third party
service provider exactly after 3 minutes i need to execute a sql query to update database.
how should i do this , any suggestions are accepted.
** is it possible using stored procedures...
Exactly the scenario is , we are having mediator service application consider it has webservice. from my application when i send a SMS to webservice application via to SMS service provider , this system will push to embedded device , this will make the system to ON. and after 2 min device will send SMS message to pur application thru SMS service provider to say that checking is going on... after receiving this message exactly i need to update database saying that chekcing done succefully. why 3 minutes because exactly after this time device will go Off.
regards,
Mahesh

How exactly are you receiving the SMS Messages. What service is picking them up.
Theres a couple of ways you could do it.
In your Application Code on the SMSReceived Event you could kick off a separate thread to sleep for 180 seconds, and then call your SQL Code.
If you want to do it in the database, you'll need some sort of polling thread.
Record the "TimeReceived" and have a bit flag "PostProcessed"
Then you could just have a job that runs every 60 seconds that goes
SELECT *
FROM ReceivedSMS
WHERE TimeRecieved < dateadd(second, -180, getdatE()) AND
PostProcessed = 0
FOREACH Record - Execute SPROC & Update PostProcessed = 1.

You can use "SQL jobs"
Look at these articles:
http://msdn.microsoft.com/en-us/library/ms187910.aspx
http://dacosta9.wordpress.com/2008/10/22/how-to-disable-or-enable-a-sql-server-job-programatically/
Hope this helps.

Run the stored proc immediately but the first T-SQL line is WAITFOR DELAY '00:03:00' ?

Related

Is it possible to apply no lock at DB/Table level for all queries hitting on thd DB /TBL

I am not sure even that this is valid question. But I will explain my situation and probable get an answer from experts like you.
We have on primes MS Dynamics installed. We are observing very slow performance.
We are looking at APP Log server. we are noticing 4-5 warning messages per second about "Query Execution time exceeded 10.seconds threshold"
Here is an example of the error and related query.
Query execution time of 27.7 seconds exceeded the threshold of 10 seconds. Thread: 109; Database: Main_MSCRM;
select
top 5001 "systemuser0".QueueId as "queueid"
, "systemuser0".CreatedBy as "createdby"
, "systemuser0".Address1_Latitude as "address1_latitude"
, "systemuser0".Address2_StateOrProvince as "address2_stateorprovince"
, "systemuser0".Address1_County as "address1_county"
, "systemuser0".Address2_Country as "address2_country"
, "systemuser0".Address2_PostOfficeBox as "address2_postofficebox"
, "systemuser0".PreferredPhoneCode as "preferredphonecode"
, "systemuser0".new_RegistrationNumer as "new_registrationnumer"
, "systemuser0".YammerUserId as "yammeruserid"
, "systemuser0".Title as "title"
, "systemuser0".SetupUser as "setupuser"
, "systemuser0".FirstName as "firstname"
, "systemuser0".EmployeeId as "employeeid"
, "systemuser0".Address1_Line2 as "address1_line2"
, "systemuser0".Address1_City as "address1_city"
, "systemuser0".YomiFirstName as "yomifirstname"
, "systemuser0".ExchangeRate as "exchangerate"
, "systemuser0".Address1_ShippingMethodCode as "address1_shippingmethodcode"
, "systemuser0".YomiMiddleName as "yomimiddlename"
, "systemuser0".Address2_Line2 as "address2_line2"
, "systemuser0".DefaultFiltersPopulated as "defaultfilterspopulated"
, "systemuser0".ModifiedOnBehalfBy as "modifiedonbehalfby"
, "systemuser0".Address2_Line3 as "address2_line3"
, "systemuser0".DefaultMailboxName as "defaultmailboxname"
from
SystemUser as "systemuser0"
where
(("systemuser0".IsDisabled = 0)) order by
"systemuser0".SystemUserId asc
Now when I run this query at SQL level, the result came up in less than 2 seconds. So my confusion is why it takes more time on CRM Front end side?
Apart from, the time that it takes for data rendering at CRM Front end level, I can not think anything else.
My Second confusion is when I run this query and other where I was getting warning messages with no lock in query itself, it was way faster than even 2 seconds.
What I am thinking is to write logic that will apply at DB level and whatever query hits the DB will have by default NO LOCK in it.
Is it possible even? PLEASE let me know how to get rid of these warning messages.
Thanks.
By running the query at SQL level I don't know whether you mean running it directly from the SQL Server console, but I think I can offer some insight as to why it appears to take longer when running on CRM Front end side. When you run the query directly from SQL Server, most of the time you already have an active connection to the database. This means that you don't have to wait to establish a connection, and the two big holdups would be waiting for the query to execute, and waiting to receive the result set.
However, when you run the query from your CRM front end, you presumably would have to establish a connection before you even begin the query. Setting up a connection can take longer than you might think.
So, a good test to run would be this: Execute your query twice, back-to-back, from the CRM front end and clock the running time of each one. If the second query runs much faster, than you may have discovered that the cost of establishing a connection with your SQL Server.
Maybe this is the same famous problem we usually get when command times out in ado.net but works fine in Management Studio. I think there are several fixes out there but since you don't have control over the query so try these 2 commands on the DB in question
DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
I would strongly recommend running a Query Execution Plan so that it'll tell you if any queries might be improved by adding indexes.
Also, why are you trying to pull 5k records at once? Is that generated from custom code or something? CRM views are way less than that, i.e. 50-200 records. By pulling so many records at once you're increasing the likelihood of having database locks.

Pulling data from a SQL table

I have an Intranet, that is SQL based on the back end.
Users submit documents to the Intranet, but sometimes they set an expiry on the document.
There is a table "dbo.article" that lists all these documents, who submitted them and when (if ever) they expire. I get get this data by doing:
SELECT TOP 999 [NEWSID]
,[EXPIRES]
,[HEADLINE]
,[AUTHORID]
,[AUTHOR]
FROM [ARTICLE]
ORDER BY [EXPIRES] ASC
I would like this to run, say once a week, and then email me when an article is about to expire.
What would be the best way to achieve this?
Gavin.
a couple of ways to achieve this,
option 1 - write a stored procedure checking the expiry and sending notification emails if necessary, there are ways to send emails from sql server, for example, this link - How to send email from SQL Server?
option 2 - use some script (vbs or powershell, again, either use stored procedure or plain sql query) and when the condition is met, fire an email, and this is more flexible and could be installed at any client machine (not necessary on the SQL server). one sample on how to send email using vbs - http://social.technet.microsoft.com/Forums/en-US/7779b3bb-dfcc-4ab3-966d-9c71d5369ad7/send-email-using-vbscript
option 3 - implement a simple console app or even win form app to do stuff in option 2, instead of using script.
but all the options require you to add a scheduled task on the installed box to run it at your desired timeframe.

Loop SQL Query For Specific Time

I have a sql query that I need to loop through the system views sys.dm_exec_requests and sys.dm_exec_sessions every 60 seconds to pull specific information and dump it into a separate table. After a specified time I would like it to kill the loop. How would the loop be formatted?
This sounds like a SQL Agent job. If so, the short form of the answer is:
Create the job with one step that runs the query
Add a Schedule that runs it once a minute, starting whenever you want it to start
Set the schedule to stop running it when the cut-off time is reached
The long form, of course, is all the detail work behind creating a SQL Agent job. Best to read up on them in Books Online (here)
Don't do this in a loop. Do it with a job.
Write a sproc that does the query and save the results and then call it from a job.
I think you should use a job as well. But some work environments that is not practical. So you could have something like:
WHILE #StopTime < getdate()
BEGIN
exec LogCurrentData
WAITFOR DELAY '00:01:00'; -- wait 1 minute
END
I think the best way is creating a Job
There is a post that explain how to create a job step by step (with images) in SQL Server.
You can visit the post here
If you prefer a video tutorial, you can visit this link

How do I monitor the age of messages in SQL Service Broker?

I have a SQL Server 2008 Service Broker queue that processes messages by calling a CLR stored procedure (which, in turn, transports the messages via HTTP to a third party's REST API). I need to get a handle on "how backed up?" or "how far behind?" this queue is. While I understand that the total number of messages in the queue is a good indicator of progress, what I'm interested in is "how long was the most recently handled message waiting in the queue to be processed?" As best I can tell, selecting from the queue gives you all of the messages in it, but does not give the age of the message. For example:
SELECT TOP 100 *, casted_message_body =
CASE message_type_name WHEN 'X'
THEN CAST(message_body AS NVARCHAR(MAX))
ELSE message_body
END
FROM [SyncReadTargetQueue] WITH(NOLOCK)
But, none of the columns indicate age.
Any ideas?
To get the time when message arrived you could use "security_timestamp" in sys.conversation_endpoints.
How to monitor Service Broker- maybe this helps.

Sync Framework between SQL Server 2008 and SQL Server CE

I'm working with a moderately sized database of about 60,000 records. I am working on building a mobile application which will be able to check out a single table into a compact .sdf on for viewing and altering on the device, then allow the user to sync their changes back up with the main server and receive any new information.
I have set it up with the Sync Framework using a WCF Service Library. When setting up the connection for some reason the database won't let me check "Use SQL Server Change Tracking" and throws up the error:
"'Unable to initialize the client database, because the schema for table 'Inventory' could >not be retrieved by the GetSchema() method of DbServerSyncProvider. Make sure that you can >establish a connection to the client database and that either the >SelectIncrementalInsertsCommand property or the SelectIncrementalUpdatesCommand property of >the SyncAdapter is specified correctly."
So I leave it unchecked and set it to use some already created columns "AddDateTime" and "LastEditTime" it seems to work okay, and after a massive amount of tweaking I have it partially working. The changes on the device sync up perfectly with the database, updates, deletes, all get applied. However, changes on the server side...never get updated. I've made sure everything is set up right with the bidirectional setup so that shouldn't be the problem. And, I let it sit overnight so the database received ~500 new records, this morning it actually synced the latest 24 entries to the database...out of 500 new. So that should be further proof that it's able to receive information from the server, but for all useful purposes, it's not.
I've tried pretty much everything and I'm honestly getting close to losing it. If anyone has any ideas they can throw out I can chase after I would be most grateful.
I'm not sure if I just need to go back and figure out why I can't do it with the "SQL Server Change Tracking". Or if there is a simple explanation for why it's not actually syncing 99% of the changes on the server back to the client.
Also, the server database table schema can't be altered as a lot of other services use it. But the compact database can be whatever the heck in needs to be to just store the table and sync properly in both directions.
Thank you!!
Quick Overview:
Using WCF and syncing without SQL Server Change Tracking (Fully enabled on server and database)
Syncing changes from client to server works perfectly
Syncing from server back to the client not so much: out of 500 new entries overnight, on a sync it downloaded 24.
EDIT: JuneT got me thinking about the time and their anchors. When I synced this morning it pulled 54 of about 300 new added records. I went in to the line (there are about 60 or so columns, so I removed them for readability, this is kind of a joke)
this.SelectIncrementalUpdatesCommand.CommandText = #"SELECT [Value], [Value], [Value] FROM >TABLE WHERE ([LastEditDate] > #sync_last_received_anchor AND [LastEditDate] <= >#sync_new_received_anchor AND [AddDateTime] <= #sync_last_received_anchor)";
And replaced #sync_last_received_anchor with two DIFFERENT times. Upon syncing it now returns the rows trapped between those two and took out the middle one giving me:
this.SelectIncrementalUpdatesCommand.CommandText = #"SELECT[Value], [Value], [Value] FROM >TABLE WHERE ([LastEditDate] > '2012-06-13 01:03:07.470' AND [AddDateTime] <= '2012-06-14 >08:54:27.727')"; (NOTE: The second date is just the current time now)
Though it returned a few hundred more rows than initially planned (set the date gap for 600, it returned just over 800). It does in fact sync the client up with the the new server changes.
Can anyone explain why I can't use #sync_last_received_anchor and what I should be looking for. I suppose I could always add box that allows the user to select the date to begin updating from? Or maybe add some sort of xml file to store the sync date that would be updated anytime a sync was -successfully- completed?
Thanks!
EDIT:
Ran the SQL profiler on it...the date (#sync_last_received_anchor) is getting set to 8 hours ahead of whatever time it really is. I have no idea how or why it's doing this, but that would definitely make sense.
Turns out the anchors are collected like this:
this.SelectNewAnchorCommand.CommandText = "Select #sync_new_received_anchor = GETUTCDATE()";
That UTC date is what was causing the 8 hours gap. To fix it either change it to GETDATE(), or convert your columns to UTC time in the WHERE clause of the commands.
After spending many hours with many cups of coffee, I've figured out how to solve this error of mine. While I was running the code on desktop testing area, everything seemed to be working perfectly; however the same code and webservice on target device gave this error repeatedly. Then, suddenly, the "dbo_" prefixes on compact database table names started looking interesting, like they were trying to tell me something really important. So, I've listened...
Configuration.SyncTables.Add("Products);
on ClientSyncAgent.cs should be changed to
Configuration.SyncTables.Add("dbo_Products");
[Exeunt]