MySQL average of non-null columns - mysql

I've kludged my way through by doing this, but I feel there's probably a cleaner/faster/better solution, and am always keen to learn:
UPDATE myTable SET fAvg =
(COALESCE(f1,0) + COALESCE(f2,0) + COALESCE(f3,0) + COALESCE(f4,0))
/
(
CASE WHEN f1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN f2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN f3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN f4 IS NOT NULL THEN 1 ELSE 0 END
)
So, how can that be improved?

You can simplify the count by taking advantage of the fact the MySQL treats booleans as integers in a numeric context:
UPDATE myTable
SET fAvg = (COALESCE(f1,0) + COALESCE(f2,0) + COALESCE(f3,0) + COALESCE(f4,0)) /
((f1 IS NOT NULL) + (f2 IS NOT NULL) + (f3 IS NOT NULL) + (F4 IS NOT NULL));

Related

IF/ CASE + math operation - Mysql

I've got 5 columns in table:
- id / a /b /operation/ c
where for example: 1 / 2 /3 / + / 5
What is my goal is to check if operation (+/-/*/%) is correct with the formula (a (operation) b = c) and show only those records where formula is true.
Honestly I've been trying to solve that but unfortunately I really don't know how to...
For sure I have to start with operation column:
(IF(operation = '+', a+b, IF( operation = '-', a-b, IF(operation = '*', a*b, IF(operation = '/',a/b, ''))))
Shall I mix it with IF CASE maybe? What's more, zero exepction needs to be added
Use case:
select (c = (case when operation = '+' then a + b
when operation = '-' then a - b
when operation = '/' then a / nullif(b, 0)
. . .
end)
) as expected_equals_actual

SQL remove the next letter/character after a character ^

How to remove a character after the character ^ from a selected rows in table?
e.g.
TABLE Things
Boat
Do^2gs
Cat^fs
^KBear
Mi^&ce
D^Rice
RESULTS:
Boat
Dogs
Cats
Bear
Mice
Dice
select case when charindex('^', col) <> 0
then stuff(col, charindex('^', col), 2, '')
else col
end
-- to handle multiple ^ up to max of 4
select t.col,
r4.col
from Things t
cross apply
(
select col = case when charindex('^', col) <> 0
then stuff(col, charindex('^', col), 2, '')
else col
end
) r1
cross apply
(
select col = case when charindex('^', r1.col) <> 0
then stuff(r1.col, charindex('^', r1.col), 2, '')
else r1.col
end
) r2
cross apply
(
select col = case when charindex('^', r2.col) <> 0
then stuff(r2.col, charindex('^', r2.col), 2, '')
else r2.col
end
) r3
cross apply
(
select col = case when charindex('^', r3.col) <> 0
then stuff(r3.col, charindex('^', r3.col), 2, '')
else r3.col
end
) r4
-- UDF to remove the ^
create function remove_chr
(
#str varchar(100)
)
returns varchar(100)
as
begin
while charindex('^', #str) <> 0
begin
select #str = case
when charindex('^', #str) <> 0
then stuff(#str, charindex('^', #str), 2, '')
else #str
end
end
return #str
end
If you are using MySQL you could use:
SELECT col,
IF(INSTR(col,'^') > 0,CONCAT(LEFT(col,INSTR(col, '^')-1),
RIGHT(col,LENGTH(col) - INSTR(col, '^')-1)), col) AS result
FROM Things;
SqlFiddleDemo
And SQL Server equivalent:
SELECT col,
IIF(CHARINDEX('^',col) > 0,CONCAT(LEFT(col,CHARINDEX('^',col)-1),
RIGHT(col,LEN(col) - CHARINDEX('^',col)-1)), col) AS result
FROM Things
LiveDemo
SQL Server 2008:
SELECT col,
CASE WHEN CHARINDEX('^',col) > 0
THEN LEFT(col,CHARINDEX('^',col)-1) + RIGHT(col,LEN(col) - CHARINDEX('^',col)-1)
ELSE col
END AS result
FROM Things;
Keep in mind that it will work only if there is none or one occurence of ^.
Here is the solution which removes any number of occurrence of '^' .
I have created a function SQL server which is not used any loop or cursor.
CREATE FUNCTION [dbo].[FnReplaceChar](#pOriginalText VARCHAR(2000))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #vText VARCHAR(1000)
,#vXML XML
--Convert text as XML format
SELECT #vXML = '<Root><dtl><f>' + REPLACE(#pOriginalText,'^','</f></dtl><dtl><f>^')+'</f></dtl></Root>'
--Splits words started with '^' and combines after removing character starts with '^'
SET #vText = (
SELECT '' + ACT_TEXT
FROM
(
SELECT CASE WHEN CHARINDEX('^',DOC.COL.value('f[1]','VARCHAR(100)') ,0) > 0
THEN STUFF(DOC.COL.value('f[1]','VARCHAR(100)'),CHARINDEX('^',DOC.COL.value('f[1]','VARCHAR(100)') ,0),2,'')
ELSE DOC.COL.value('f[1]','VARCHAR(100)')
END AS ACT_TEXT
FROM #vXML.nodes('/Root/dtl') DOC(COL)
)T
FOR XML PATH('')
)
RETURN #vText
END
You can use this function in your select query
SELECT dbo.[FnReplaceChar](col_Name)
FROM [Things]

How to check negative values in mysql and decide the output after that

I am using a mysql case for some calculation and my demand is that if the output is negative then i will show 0 in the place of the negative column.Otherwise the positive value.
Let me post the query:
select
concat(jo.title,' (', CCP.name, ')'), PL.analyst, PL.consultant,
PL.csm,
(CASE
WHEN PL.productType like 'Staffing' THEN (SELECT ((DATEDIFF(PL.dateEnd, PL.dateClientEffective)) -((WEEK(PL.dateEnd) - WEEK(PL.dateClientEffective)) * 2) - (case when weekday(PL.dateEnd) = 6 then 1 else 0 end) - (case when weekday(PL.dateClientEffective) = 5 then 1 else 0 end)) as DifD) * 8 * (PL.clientBillRate-PL.payRate) ELSE (PL.salary*PL.fee)END) Value
Now if the value is negative, then it should show 0 else will show the original value
The simplest way is simply to use greatest():
select greatest(<expression>, 0) as col
It is unclear what column/expression you want to do this for in your query. But, you can just plug it in.
The advantage of this method over other methods is:
The only needs to appear once in the query. Not having to duplicate code reduces the likelihood of errors.
There is no need for a subquery. This is an issue in MySQL only because MySQL materializes subqueries.
Simply use SIGN() in mysql
It returns 1 as a positive value and -1 is a negative value
Example
SELECT SIGN(500); -- (Output is 1)
SELECT SIGN(2500); -- (Output is 1)
SELECT SIGN(-999); -- (Output is -1)
SELECT SIGN(-5); -- (Output is -1)
please check this, haven't tested yet.
Note: this might not be the best solution
select concat(jo.title,' (', CCP.name, ')'), PL.analyst, PL.consultant, PL.csm,
if(
(CASE WHEN PL.productType like 'Staffing' THEN (SELECT ((DATEDIFF(PL.dateEnd, PL.dateClientEffective)) -((WEEK(PL.dateEnd) - WEEK(PL.dateClientEffective)) * 2) -
(case when weekday(PL.dateEnd) = 6 then 1 else 0 end) -
(case when weekday(PL.dateClientEffective) = 5 then 1 else 0 end)) as DifD) * 8 * (PL.clientBillRate-PL.payRate) ELSE (PL.salary*PL.fee)END)
< 0,0,
(CASE WHEN PL.productType like 'Staffing' THEN (SELECT ((DATEDIFF(PL.dateEnd, PL.dateClientEffective)) -((WEEK(PL.dateEnd) - WEEK(PL.dateClientEffective)) * 2) -
(case when weekday(PL.dateEnd) = 6 then 1 else 0 end) -
(case when weekday(PL.dateClientEffective) = 5 then 1 else 0 end)) as DifD) * 8 * (PL.clientBillRate-PL.payRate) ELSE (PL.salary*PL.fee)END)
) Value
Just do like this :
select temp.* , --all your columns
if(temp.value<0,0,temp.value) as Value
from
( your query mentioned above) temp;

Order SQL result with point system

I'm trying to get my SQL result to be ordered by a certain 'point-system'. For every field that's filled in, the search result gets a certain amount of points. At the end of my SQL I add the following ORDER BY - code, however, if I change one of the '1'-numbers to a higher number, the search result order isn't changed. Why wouldn't that work? (Changed the bedrijfslogo-case to 9 in this example):
Thanks guys!
$sql .= " ORDER BY
case when ID is not null then 1 else 0 end +
case when username is not null then 1 else 0 end +
case when password is not null then 1 else 0 end +
case when voornaam is not null then 1 else 0 end +
case when achternaam is not null then 1 else 0 end +
case when telefoonnummerP is not null then 1 else 0 end +
case when emailP is not null then 1 else 0 end +
case when functie is not null then 1 else 0 end +
case when bedrijfsnaam is not null then 1 else 0 end +
case when bedrijfsslogan is not null then 1 else 0 end +
case when bedrijfslogo is not null then 9 else 0 end +
case when bedrijfsfoto is not null then 1 else 0 end +
case when bedrijfsfoto2 is not null then 1 else 0 end +
case when bedrijfsfoto3 is not null then 1 else 0 end +
case when bedrijfsfoto4 is not null then 1 else 0 end +
case when bedrijfsomschrijving is not null then 1 else 0 end +
case when bedrijfsspecialiteiten is not null then 1 else 0 end +
case when bedrijfsgeschiedenis is not null then 1 else 0 end +
case when openingstijden is not null then 1 else 0 end +
case when kvk is not null then 1 else 0 end +
case when straatnaam is not null then 1 else 0 end +
case when huisnummer is not null then 1 else 0 end +
case when postcode is not null then 1 else 0 end +
case when plaats is not null then 1 else 0 end +
case when nevenvestigingen is not null then 1 else 0 end +
case when telefoonnummer is not null then 1 else 0 end +
case when fax is not null then 1 else 0 end +
case when email is not null then 1 else 0 end +
case when website is not null then 1 else 0 end +
case when twitter is not null then 1 else 0 end +
case when facebook is not null then 1 else 0 end +
case when youtube is not null then 1 else 0 end +
case when linkedin is not null then 1 else 0 end +
case when hoofdrubriek is not null then 1 else 0 end +
case when subrubrieken is not null then 1 else 0 end +
case when merken is not null then 1 else 0 end +
case when diensten is not null then 1 else 0 end +
case when productsoorten is not null then 1 else 0 end +
case when brancheverenigingen is not null then 1 else 0 end
DESC";
Maybe bedrijfslogo is empty in the table? :)
If you add the casing to a view instead it might be easier to find the error.
create view myView as
select *, (CASE when ID is not null then 1 else 0 end + ... n) AS SortPoints
from table
GO
select * from myView order by SortPoints desc

SSRS 2008 R2 Get Human Readable Schedule Information from ReportServer DB

I am looking to extract "human readable" schedule information from the ReportServer.dbo.Schedule table using t-sql.
An example of "human readable" follows.
At 6:02 AM every Sun, Mon, Tue, Wed, Thu, Fri, Sat of every week, starting 2/28/2011
There are a bunch of numeric fields in the table which are used to store the schedule, but I would like to convert those to words, as in my example.
Has anyone ever done this with reporting services?
SQL is not great for string manipulation or bitwise operations, and parsing this table requires a moderate bit of both. I'm sure SSRS doesn't do this in SQL: I probably could have written this in half the time and half the lines in C#.
USE ReportServer;
WITH EnhancedSched
AS (
SELECT
dbo.Schedule.ScheduleID ,
dbo.Schedule.Name ,
dbo.Schedule.StartDate ,
dbo.Schedule.Flags ,
dbo.Schedule.NextRunTime ,
dbo.Schedule.LastRunTime ,
dbo.Schedule.EndDate ,
dbo.Schedule.RecurrenceType ,
dbo.Schedule.MinutesInterval ,
dbo.Schedule.DaysInterval ,
dbo.Schedule.WeeksInterval ,
dbo.Schedule.DaysOfWeek ,
dbo.Schedule.DaysOfMonth ,
dbo.Schedule.Month ,
dbo.Schedule.MonthlyWeek ,
dbo.Schedule.State ,
dbo.Schedule.LastRunStatus ,
dbo.Schedule.ScheduledRunTimeout ,
dbo.Schedule.CreatedById ,
dbo.Schedule.EventType ,
dbo.Schedule.EventData ,
dbo.Schedule.Type ,
dbo.Schedule.ConsistancyCheck ,
dbo.Schedule.Path ,
CASE WHEN DaysOfWeek & 1 <> 0 THEN 'Sun, '
ELSE ''
END + CASE WHEN DaysOfWeek & 2 <> 0 THEN 'Mon, '
ELSE ''
END + CASE WHEN DaysOfWeek & 4 <> 0 THEN 'Tue, '
ELSE ''
END + CASE WHEN DaysOfWeek & 8 <> 0 THEN 'Wed, '
ELSE ''
END
+ CASE WHEN DaysOfWeek & 16 <> 0 THEN 'Thu, '
ELSE ''
END + CASE WHEN DaysOfWeek & 32 <> 0 THEN 'Fri, '
ELSE ''
END + CASE WHEN DaysOfWeek & 64 <> 0 THEN 'Sat, '
ELSE ''
END AS DaysOfWeekString ,
CASE WHEN DaysOfMonth & 1 <> 0 THEN '1,'
ELSE ''
END + CASE WHEN DaysOfMonth & 2 <> 0 THEN '2,'
ELSE ''
END + CASE WHEN DaysOfMonth & 4 <> 0 THEN '3,'
ELSE ''
END + CASE WHEN DaysOfMonth & 8 <> 0 THEN '4,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 16 <> 0 THEN '5,'
ELSE ''
END + CASE WHEN DaysOfMonth & 32 <> 0 THEN '6,'
ELSE ''
END + CASE WHEN DaysOfMonth & 64 <> 0 THEN '7,'
ELSE ''
END + CASE WHEN DaysOfMonth & 128 <> 0 THEN '8,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 256 <> 0 THEN '9,'
ELSE ''
END + CASE WHEN DaysOfMonth & 512 <> 0 THEN '10,'
ELSE ''
END + CASE WHEN DaysOfMonth & 1024 <> 0 THEN '11,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 2048 <> 0 THEN '12,'
ELSE ''
END + CASE WHEN DaysOfMonth & 4096 <> 0 THEN '13,'
ELSE ''
END + CASE WHEN DaysOfMonth & 8192 <> 0 THEN '14,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 16384 <> 0 THEN '15,'
ELSE ''
END + CASE WHEN DaysOfMonth & 32768 <> 0 THEN '16,'
ELSE ''
END + CASE WHEN DaysOfMonth & 65536 <> 0 THEN '17,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 131072 <> 0 THEN '18,'
ELSE ''
END + CASE WHEN DaysOfMonth & 262144 <> 0 THEN '19,'
ELSE ''
END + CASE WHEN DaysOfMonth & 524288 <> 0 THEN '20,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 1048576 <> 0 THEN '21,'
ELSE ''
END + CASE WHEN DaysOfMonth & 2097152 <> 0 THEN '22,'
ELSE ''
END + CASE WHEN DaysOfMonth & 4194304 <> 0 THEN '23,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 8388608 <> 0 THEN '24,'
ELSE ''
END + CASE WHEN DaysOfMonth & 16777216 <> 0 THEN '25,'
ELSE ''
END + CASE WHEN DaysOfMonth & 33554432 <> 0 THEN '26,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 67108864 <> 0 THEN '27,'
ELSE ''
END + CASE WHEN DaysOfMonth & 134217728 <> 0 THEN '28,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 268435456 <> 0 THEN '29,'
ELSE ''
END + CASE WHEN DaysOfMonth & 536870912 <> 0 THEN '30,'
ELSE ''
END
+ CASE WHEN DaysOfMonth & 1073741824 <> 0 THEN '31,'
ELSE ''
END AS DaysOfMonthString ,
CASE WHEN Month = 4095 THEN 'every month, '
ELSE CASE WHEN Month & 1 <> 0 THEN 'Jan, '
ELSE ''
END + CASE WHEN Month & 2 <> 0 THEN 'Feb, '
ELSE ''
END + CASE WHEN Month & 4 <> 0 THEN 'Mar, '
ELSE ''
END
+ CASE WHEN Month & 8 <> 0 THEN 'Apr, '
ELSE ''
END + CASE WHEN Month & 16 <> 0 THEN 'May, '
ELSE ''
END + CASE WHEN Month & 32 <> 0 THEN 'Jun, '
ELSE ''
END
+ CASE WHEN Month & 64 <> 0 THEN 'Jul, '
ELSE ''
END + CASE WHEN Month & 128 <> 0 THEN 'Aug, '
ELSE ''
END
+ CASE WHEN Month & 256 <> 0 THEN 'Sep, '
ELSE ''
END + CASE WHEN Month & 512 <> 0 THEN 'Oct, '
ELSE ''
END
+ CASE WHEN Month & 1024 <> 0 THEN 'Nov, '
ELSE ''
END + CASE WHEN Month & 2048 <> 0 THEN 'Dec, '
ELSE ''
END
END AS MonthString ,
CASE MonthlyWeek
WHEN 1 THEN 'first'
WHEN 2 THEN 'second'
WHEN 3 THEN 'third'
WHEN 4 THEN 'fourth'
WHEN 5 THEN 'last'
END AS MonthlyWeekString ,
' starting ' + CONVERT (VARCHAR, StartDate, 101)
+ CASE WHEN EndDate IS NOT NULL
THEN ' and ending ' + CONVERT (VARCHAR, EndDate, 101)
ELSE ''
END AS StartEndString ,
CASE CONVERT(VARCHAR, DATEPART(HOUR, StartDate) % 12)
WHEN 0 THEN '12'
ELSE CONVERT(VARCHAR, DATEPART(HOUR, StartDate) % 12)
END + ':'
+ CASE WHEN DATEPART(MINUTE, StartDate) < 10
THEN '0' + CONVERT(VARCHAR(2), DATEPART(MINUTE,
StartDate))
ELSE CONVERT(VARCHAR(2), DATEPART(MINUTE, StartDate))
END + CASE WHEN DATEPART(HOUR, StartDate) >= 12 THEN ' PM'
ELSE ' AM'
END AS StartTime
FROM
Schedule
),
SuperEnhancedSchedule
AS (
SELECT
EnhancedSched.ScheduleID ,
EnhancedSched.Name ,
EnhancedSched.StartDate ,
EnhancedSched.Flags ,
EnhancedSched.NextRunTime ,
EnhancedSched.LastRunTime ,
EnhancedSched.EndDate ,
EnhancedSched.RecurrenceType ,
EnhancedSched.MinutesInterval ,
EnhancedSched.DaysInterval ,
EnhancedSched.WeeksInterval ,
EnhancedSched.DaysOfWeek ,
EnhancedSched.DaysOfMonth ,
EnhancedSched.Month ,
EnhancedSched.MonthlyWeek ,
EnhancedSched.State ,
EnhancedSched.LastRunStatus ,
EnhancedSched.ScheduledRunTimeout ,
EnhancedSched.CreatedById ,
EnhancedSched.EventType ,
EnhancedSched.EventData ,
EnhancedSched.Type ,
EnhancedSched.ConsistancyCheck ,
EnhancedSched.Path , -- spec what you need.
CASE WHEN RecurrenceType = 1
THEN 'At ' + StartTime + ' on '
+ CONVERT(VARCHAR, StartDate, 101)
WHEN RecurrenceType = 2
THEN 'Every ' + CONVERT(VARCHAR, ( MinutesInterval / 60 ))
+ ' hour(s) and '
+ CONVERT(VARCHAR, ( MinutesInterval % 60 ))
+ ' minute(s), ' + 'starting '
+ CONVERT (VARCHAR, StartDate, 101) + ' at '
+ SUBSTRING(CONVERT(VARCHAR, StartDate, 8), 0, 6)
+ ' ' + SUBSTRING(CONVERT(VARCHAR, StartDate, 109),
25, 2)
+ CASE WHEN EndDate IS NOT NULL
THEN ' and ending '
+ CONVERT (VARCHAR, EndDate, 101)
ELSE ''
END
WHEN RecurrenceType = 3
THEN 'At ' + StartTime + ' every '
+ CASE DaysInterval
WHEN 1 THEN 'day, '
ELSE CONVERT(VARCHAR, DaysInterval) + ' days, '
END + StartEndString
WHEN RecurrenceType = 4
THEN 'At ' + StartTime + ' every '
+ CASE WHEN LEN(DaysOfWeekString) > 1
THEN LEFT(DaysOfWeekString,
LEN(DaysOfWeekString) - 1)
ELSE ''
END + ' of every '
+ CASE WHEN WeeksInterval = 1 THEN ' week,'
ELSE CONVERT(VARCHAR, WeeksInterval)
+ ' weeks,'
END + StartEndString
WHEN RecurrenceType = 5
THEN 'At ' + StartTime + ' on day(s) '
+ CASE WHEN LEN(DaysOfMonthString) > 1
THEN LEFT(DaysOfMonthString,
LEN(DaysOfMonthString) - 1)
ELSE ''
END + ' of ' + MonthString + StartEndString
WHEN RecurrenceType = 6
THEN 'At ' + StartTime + ' on the ' + MonthlyWeekString
+ ' '
+ CASE WHEN LEN(DaysOfWeekString) > 1
THEN LEFT(DaysOfWeekString,
LEN(DaysOfWeekString) - 1)
ELSE ''
END + ' of ' + MonthString + StartEndString
ELSE 'At ' + SUBSTRING(CONVERT(VARCHAR, StartDate, 8), 0,
6) + ' '
+ SUBSTRING(CONVERT(VARCHAR, StartDate, 109), 25, 2)
+ StartEndString
END ScheduleTextDefinition
FROM
EnhancedSched
)
SELECT
*
-- This has the same columns as the native [dbo].Schedule table plus a field called "SheduleTextDefinition"
-- You can use "SuperEnhancedSchedule" in place of the usual SSRS.Schedule table, joining to subscriptions and such.
FROM
SuperEnhancedSchedule
This post may be very old, but it helped me out today!
I found 2 items that I would like to add in the excellent post above by Jamie F for his CTE.
There was a missing entry for day 31 that needs to be added in as part of the EnhancedSched CTE, the below needs to be added to the end of the 'DaysOfMonthString'
+ CASE WHEN DaysOfMonth & 1073741824 <> 0 THEN '31,' ELSE '' END
Also, the 'StartTime' column definition with the modulo 12 makes any time beginning with 12 a zero, so the plain English result shows a start time of 0:30 PM for something that is supposed to say 12:30 pm.
Replace the
CONVERT(VARCHAR, DATEPART(hour, StartDate) % 12)
with
CASE CONVERT(VARCHAR, DATEPART(hour, StartDate) % 12) WHEN 0 THEN '12' ELSE CONVERT(VARCHAR, DATEPART(hour, StartDate) % 12) END
to get the plain English start time to read properly.
Mega thanks to Jamie F's post above, saved my bacon. +1 internets for you good sir.
Sorry for the extra 'answer' post, no rep to comment to up-vote Jamie F's excellent post above.
There's actually a stored procedure in the MSDB database called sp_get_schedule_description that can generate the schedule descriptions. I have the code below writting the schedule ID and the human-readable description to a ScheduleInfo user table. It works very well but the user running the code will need read-access to the msdb database and execute permissions to the SP for it to work.
DECLARE #schedule_description NVARCHAR(255)
DECLARE #freq_type INT
DECLARE #freq_interval INT
DECLARE #freq_subday_type INT
DECLARE #freq_subday_interval INT
DECLARE #freq_relative_interval INT
DECLARE #freq_recurrence_factor INT
DECLARE #active_start_date INT
DECLARE #active_end_date INT
DECLARE #active_start_time INT
DECLARE #active_end_time INT
DECLARE #schedule_id_as_char VARCHAR(10)
DECLARE #scheduleID UNIQUEIDENTIFIER
DECLARE #resultCursor CURSOR
-- Create cursor using records from job schedules in MSDB database
--
SET #resultCursor = CURSOR FOR
SELECT
d.freq_type
,d.freq_interval
,d.freq_subday_type
,d.freq_subday_interval
,d.freq_relative_interval
,d.freq_recurrence_factor
,d.active_start_date
,d.active_end_date
,d.active_start_time
,d.active_end_time
,a.ScheduleID
FROM ReportServer.dbo.Schedule a
JOIN msdb.dbo.sysjobs b on CONVERT(NVARCHAR(128),a.ScheduleID) = b.name
JOIN msdb.dbo.sysjobschedules c on b.job_id = c.job_id
JOIN msdb.dbo.sysschedules d on c.schedule_id = d.schedule_id
OPEN #resultCursor
-- Fetch first record from cursor
--
FETCH NEXT
FROM #resultCursor INTO
#freq_type
,#freq_interval
,#freq_subday_type
,#freq_subday_interval
,#freq_relative_interval
,#freq_recurrence_factor
,#active_start_date
,#active_end_date
,#active_start_time
,#active_end_time
,#scheduleID
-- Loop through cursor and get the rest of the records
--
WHILE ##FETCH_STATUS = 0
BEGIN
-- Call stored prc in MSDB database to get schedule description
--
EXECUTE msdb.dbo.sp_get_schedule_description
#freq_type,
#freq_interval,
#freq_subday_type,
#freq_subday_interval,
#freq_relative_interval,
#freq_recurrence_factor,
#active_start_date,
#active_end_date,
#active_start_time,
#active_end_time,
#schedule_description OUTPUT
-- Insert record to ScheduleInfo table
--
INSERT INTO ScheduleInfo VALUES (#scheduleID, #schedule_description)
-- Get the next record from the cursor
--
FETCH NEXT
FROM #resultCursor INTO
#freq_type
,#freq_interval
,#freq_subday_type
,#freq_subday_interval
,#freq_relative_interval
,#freq_recurrence_factor
,#active_start_date
,#active_end_date
,#active_start_time
,#active_end_time
,#scheduleID
END
--Close cursor
--
CLOSE #resultCursor
DEALLOCATE #resultCursor
I have a solution for this as it came up for a report I am writing.
create function [dbo].[calendarlist](#Value_in as int,#Type as int) returns varchar(200)
as
begin
/*
This code is to work out either the day of the week or the name of a month when given a value
Wrriten by S Manson.
31/01/2012
*/
declare #strings as varchar(200)
declare #Count int
if #Type = 2 --Months
Begin
set #Count =12
end
else if #Type = 1 --Days of Week
Begin
Set #Count = 7
End
else --Days of Month
Begin
Set #Count = 31
End
set #strings = ''
while #Count<>0
begin
if #Value_in>=(select power(2,#count-1))
begin
set #Value_in = #Value_in - (select power(2,#count-1))
If #Type=2
Begin
set #strings = (SELECT DATENAME(mm, DATEADD(month, #count-1, CAST('2008-01-01' AS datetime)))) + ',' + #strings
end
else if #Type = 1
begin
set #strings = (SELECT DATENAME(dw, DATEADD(day, #count-1, CAST('2012-01-01' AS datetime)))) + ',' + #strings
end
else
begin
set #strings = convert(varchar(2),#Count) + ', ' + #strings
end
end
set #count = #count-1
end
if right(#strings,1)=','
set #strings = left(#strings,len(#strings)-1)
return #strings
end