Stored procedure - to print my result from SQL query - sql

select count(*) as count
from [dbo].[DATA_received] where DATEDIFF(MINUTE, DATE_TIME GETDATE()) <= 1
I want to run this in some frequency to check whether I am receiving data in DB.
I want to write stored procedure where if my results 0 then ,"No data received"
If the count is >0 then it should print "Data received"

Not sure how you're going to make SolarWinds do something with this output or run it every minute, but there is absolutely no reason to count how many rows were added in the last minute if you only need to know whether at least one such row exists... and you really should never apply formulae like DATEDIFF to a column, it will force the query to scan the entire table every time:
SELECT MessageToPrint = CASE WHEN EXISTS
(
SELECT 1 FROM dbo.DATA_received
WHERE DATE_TIME >= DATEADD(MINUTE, -1, sysutcdatetime())
) THEN 'Data received.' ELSE 'No data received.' END;

Related

How to increase the duration logic in SQL SP

I have a stored procedure which deletes the records from DB based on following logic.
Select Id into #deleterecords from pricetable where
((Convert(date, modifiedon) <> convert(date,gatedate())
I would like to add one more day in Gatedate()
I’m trying in this
Select Id into #deleterecords from pricetable where
((Convert(date, modifiedon) < > convert(date,gatedate()+1)
It’s not working.
How can I add one more day?
What do you mean by "It’s not working."? Are you getting some error message?
Did you mean to write GETDATE() (the built-in function that returns the current timestamp), or you indeed have a gatedate() function in your database?
To add a day to a datetime value in SQL Server use the function DATEADD.
select Id
into #deleterecords
from pricetable
where
convert(date, modifiedon) <> convert(date, DATEADD(day, 1, gatedate()))
;

Using the result of a query to determine a value in a where clause in SQL?

So basically I've got a query where I want to filter using a date, however that date may change depending on what datas in the system.
If there's no records with a date of >='X', I want to use >='Y' instead
Currently I've got something like the following mess (Pseudocoded down to avoid using actual table names and such)
With a as (SELECT
count(column_id) as num
FROM tableA
WHERE ADate >= getdate() - 8)
,
b as (SELECT
case when num = '0' then getdate() - 15 else getdate() - 8 end as DateToUseInQuery
from A)
SELECT *
FROM tableB
Bunch of joins to other tables
WHERE BDate >= DateToUseInQuery
The general idea being is if there's no records for the week beforehand, use 2 weeks beforehand
I tried using a query within the where clause like:
WHERE BDate >= (SELECT DateToUseInQuery FROM b)
But the query ran for 11 minutes before I stopped it (Up from about 18 seconds before I tried to put this extra bit in)
I've been thinking about trying to set a variable as the date, but I can't do it in a CTE, and when I do it after, it breaks everything else.
So basically:
Is there an easier way to do this than the cack-handed way I'm trying?
If my way is fine, how can I pass that date properly into the WHERE clause?
You could try something like this. I am using a nested select and case statement to determine the number of days.
There may be a prettier way, but this works.
SELECT COUNT(column_id) AS num FROM TableA
WHERE ADate >=
DATEADD(Day,
(SELECT
CASE
WHEN EXISTS(
SELECT 1 FROM TableA
WHERE ADate >= DATEADD(Day,-8,GETDATE()))
THEN -8
ELSE -15
END AS 'dt')
,GETDATE());

SQL Server stored procedure to analyze live streaming data and reporting differences

I have a live data stream on a 2 minutes interval, that I wish to analyze in (near) real time. A snippet of this data is shown here:
This data is getting stored in a SQL Server table.
Now, I am trying to code a stored procedure in SQL Server 2008 that fulfills this condition:
Highest - Max(Start,End) > Absolute Value(Start - End),
ITEM3 fulfills this condition.
Additionally, for ALL the items which fulfill the above condition, it should then go back in time and return the start of the first record which fulfills the condition of End (Value) > Start (Value)
So, in the case above, the value returned should be 209.1 & Item 3.
The condition is getting fulfilled for ITEM3 only in the above case #10:21 A.M.
Additional note: for the purpose of this query, the values of lowest are not being used.
Also, there are no Zero / Null values in this data stream (the .. is temporarily there).
With my limited knowledge on SQL subqueries etc, I am unable to get the desired result beyond the first condition.
select desc
from table1
where Highest - dbo.InlineMax(Start,End) > abs(Start- End)
InlineMax is my UDF which returns the higher value.
TIA
This should get you what you want.
SELECT
[desc], [highest], [start], [end]
FROM
items
GROUP BY
[desc], [highest], [start], [end]
HAVING
(MAX([start]) > MAX([end]) and highest - MAX([start]) > ABS([start]-[end]))
OR
(MAX([start]) <= MAX([end]) and highest - MAX([end]) > ABS([start]-[end]))
group by the relevant columns and then filter it out using the having clause.
If max(start) > max(end) then require highest - max(start) > abs(start-end)
If max(start) <= max(end) then require highest - max(end) > abs(start-end)

In Microsoft SQL Server, how to split rows using datetime data

As I am working on a project for my university, I am supposed to create a dashboard for machines downtime.
Every time that a machine is down during the day, the availability is calculated as [ 24 (hours) - Downtime / 24 (hours) ].
However, there are some situations where the machines are down more than 1 day, so it means that I have the split the number of hours that machine is down and distributed to the respective days.
Here is what the data looks like:
Here is what the result looks like:
My idea,
Create one temp table with number between specific range by SELECT DISTINCT SeqDateDiff = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 1000.
PS: the range is 0 to 1000 in the sample, you can create wider range, but it should not be neccessary, you can consider remove the machine if already down over 1000 days. And there are some other methods to create this kind of range table, you can google it.
Then left join with your table with date difference by on target.DateDiff+1>seq.SeqDateDiff.
Then the rest is simple, just calculate out reported/completed based on different situations.
Check working sample at SQL fiddler.
Below is the codes:
select ServiceID,
case when SeqDateDiff>0 then cast(DATEADD(day, SeqDateDiff, Reported) As Date) else Reported end Started,
case when SeqDateDiff=DateDiff
then Completed
else DATEADD(second, -1, cast(cast(DATEADD(day, SeqDateDiff+1, Reported) As Date) as DateTime))
end Completed,
DateDiff, SeqDateDiff
from (select ServiceID, Completed, Reported, DATEDIFF(day, Reported, Completed) DateDiff from YourTable) target
left join (
SELECT DISTINCT SeqDateDiff = number FROM master..[spt_values] WHERE number BETWEEN 0 AND 1000
) seq on target.DateDiff+1>seq.SeqDateDiff
select case when datediff(hh, reported, completed)>12 then 12 else
datediff(hh, reported, completed) end from yourtable
if day(reported)<>day(completed)
begin
select datediff(hh, cast(completed as date), completed) from yourtable
end
Assuming it's never down more than 2 days. If so, adjust logic accordingly...

how do i get my customer records to still appear in the table beyond the 5 days advance period

I have a query that pull out all customers records I will need to call within the next 5 days in the where clause as:
Remind to call =< DATEADD(DD,5,GETDATE() and
Remind to call >= GETDATE()
The way i want it to work is that i want all customers records that i need to call 5 days in advance from GETDATE(). Once it has entered the table, it needs to stay in the table until users enters a date for the 'Confirmstart' field on web application.
What happens is my query displays the data as it should except it removes the customers record after the 5 days where i want the records to remain until the user has entered a date for the 'ConfirmStart' field
For example - Lets say todays date is 03/08/2016 where I want to pull out the customers i need to call within the next 5 days, therefore in my where clause i wrote:
<Remind to call =< DATEADD(DD,5,GETDATE() and
<Remind to call >= GETDATE()
The Dateadd should pull out records up to 08/08/2016. t also say record iD called 'CR1' that has a RemindToCall date 08/08/2013 meet this criteria.
The 'CR1' record appears in the table which is great. However when GETDATE() reaches the 9/08/2016, the 'CR1' record disappears from the table when i want it to still remain in that table until the 'ConfirmedStart' date is entered.
How do i get my customer records to still appear in the table beyond the 5 days advance period even though i need the records to appear 5 days in advance?
Further Information:
To elaborate on my above example - here is the SQL code that for the 'CR1' record but instead of it being named 'CR1' in this live example its CoS ID record called'1232' - everything else remains the same:
SELECT
CoSID,
SurName,
FirstName,
EmailAddress,
CONVERT (varchar,UKAddressDeadline,103) as UKAddressDeadline,
CONVERT (varchar,PlacementStart,103) as PlacementStart,
CONVERT (varchar,PlacementEnd,103) as PlacementEnd,
CONVERT (varchar,RemindToCall,103) as RemindToCall,
ExtReference,
HostOrgName,
UKEndorsement,
PaymentUKBA
FROM
dbo.tbl_CoS
WHERE
RemindToCall between CAST('2016-08-03' AS DATE) and DateAdd(DD,+5, CAST('2016-08-03' AS DATE)) AND
(CoSNotRequired is null and
AppWithdrawn = 0 and
CoSWithdrawn = 0 and
VisaRejected = 0 and
UKAddressDeadline is not null AND
ConfirmedStart is NULL OR
UKEndorsement is NULL)
SQL RESULT of above
I hope this extra information/details help you.
Thanks people :D
assuming that the Confirmstart is null when no value are entered.
Add that to your where clause
WHERE
(
(
[Remind to call] =< DATEADD(DD,5,GETDATE() and
[Remind to call] >= GETDATE()
)
OR
(
Confirmstart IS NULL
)
)
Maybe you need something like this:
([Remind to call] =< DATEADD(DD,5,GETDATE() and
[Remind to call] > CONVERT(varchar(8), GETDATE(), 112)) or
ConfirmStart is Null
In other words, you have to pass in the second line not GetDate(), but 08/08/2016 00:00:00