Mysql Function returning same value - mysql

I am in need of mysql function but gives same value every time
this mysql function gives me same value every time i.e. S_Start_ToBeStarted (Value of 1st If)
-- colorA
DELIMITER $$
DROP FUNCTION IF EXISTS `colorA`$$
CREATE FUNCTION `colorA`(
Appf VARCHAR(3),
Start_Datef DATETIME,
PDCf DATETIME
) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE finalcolor INT DEFAULT 0;
IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL' = 'NULL' & sysdate() <= PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_ToBeStarted` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') = 'NULL' & sysdate() > PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_Error` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') != 'NULL' & sysdate() <= PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_Ok` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE IF Appf = 'Yes' & IFNULL(Start_Datef, 'NULL') != 'NULL' & sysdate() > PDCf
THEN SET finalcolor = (SELECT `PP_Colors`.`S_Start_LateStarted` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
ELSE SET finalcolor = (SELECT `PP_Colors`.`S_NotApplicable` FROM `SCR_Sap`.`PP_Colors` LIMIT 1);
END IF;
END IF;
END IF;
END IF;
RETURN finalcolor;
END$$
DELIMITER ;

Null doesn't work well with = and != operators, the result of foobar=NULL is NULL (unknown) not true or false. Use IS NULL and IS NOT NULL instead

Related

order by not working in stored procedure mysql

select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null end as TxnType,
case when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case when tr.OperationType='7' then tr.Amount
else null end as RefundAmount,
case when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
ORDER BY
CASE WHEN sortField = 'TransactionDate' AND sortDirection='ASC' THEN TransactionDate END ASC,
CASE WHEN sortField = 'TransactionDate' AND sortDirection='DESC' THEN TransactionDate END DESC
If I apply order by clause outside the stored procedure it works fine but inside the sp it didn't work (applying order by desc on TransactionDate not working)
Try creating your stored procedure like below then
DELIMITER //
CREATE PROCEDURE select_whatever(sortField VARCHAR(20), sortDirection CHAR(4))
BEGIN
DECLARE select_clause TEXT;
DECLARE order_by_clause VARCHAR(100);
SET select_clause = "
select
tr.TransactionId as TxnIdentifier,
m.MerchantName as MerchantName,
case
when tr.ChannelType=2 then 'ACH'
when tr.ChannelType=3 then 'CC'
when tr.ChannelType=4 then 'Debit'
else null
end as ChannelType,
tr.CaptureAmount as CaptureAmount,
case
when tr.OperationType=0 then 'Sale'
when tr.OperationType=1 then 'Verify only'
when tr.OperationType=2 then 'ForceSale'
when tr.OperationType=3 then 'Adjust'
when tr.OperationType=4 then 'Activate'
when tr.OperationType=5 then 'Deactivate'
when tr.OperationType=6 then 'Reload'
when tr.OperationType=7 then 'Refund'
when tr.OperationType=8 then 'Inquire'
else null
end as TxnType,
case
when tr.TransactionStatus=0 then 'Created'
when tr.TransactionStatus=1 then 'Pending'
when tr.TransactionStatus=2 then 'Authorized'
when tr.TransactionStatus=3 then 'Posted'
when tr.TransactionStatus=4 then 'Accepted'
when tr.TransactionStatus=5 then 'Failed'
when tr.TransactionStatus=6 then 'Returned'
when tr.TransactionStatus=7 then 'Chargeback'
when tr.TransactionStatus=8 then 'Void'
when tr.TransactionStatus=9 then 'Refunded'
when tr.TransactionStatus=10 then 'Approved'
when tr.TransactionStatus=11 then 'Void attempted'
when tr.TransactionStatus=12 then 'Refund attempted'
when tr.TransactionStatus=13 then 'Hold'
when tr.TransactionStatus=14 then 'Denied'
when tr.TransactionStatus=15 then 'Settlement hold'
when tr.TransactionStatus=16 then 'Success'
when tr.TransactionStatus=17 then 'Retried'
when tr.TransactionStatus=100 then 'Unknown'
else null
end as TxnStatus,
tr.PreAuthCode as AuthCode,
DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s') as TransactionDate,
case
when tr.OperationType='7' then tr.Amount
else null
end as RefundAmount,
case
when tr.OperationType='7'
then DATE_FORMAT(tr.TransactionDate, '%m-%d-%Y %H:%i:%s')
else null
end as RefundedOn,
tr.TraceNumber as TraceNumber
from TransactionEntity tr
inner join `enter code here`DOMAIN.Merchant m on m.Id=tr.MerchantId where 1=1
and (tr.MerchantId = merchantId or merchantId=0)
and (tr.ChannelType = channelType or channelType=0)
And (tr.TransactionDate >= startDate or startDate is null)
And (tr.TransactionDate <= endDate or endDate is null)
";
SET order_by_clause = "ORDER BY";
IF sortField = "TransactionDate" AND sortDirection="ASC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate ASC")
ELSEIF sortField = "TransactionDate" AND sortDirection="DESC" THEN
SET order_by_clause = CONCAT(order_by_clause, " TransactionDate DESC")
END IF
SET #dynamic_sql = CONCAT(select_clause, ' ', order_by_clause);
PREPARE select_whatever_statement
FROM #dynamic_sql;
EXECUTE select_whatever_statement;
DEALLOCATE PREPARE select_whatever_statement;
END //
DELIMITER ;

How to two used while Syntax in Mysql Procecure

I would like to write two While Syntax.
The results I expect are as follows.
when 'H'
tagName1, tagName2, tagname3
when 'D'
tagName1, tagName2, tagname3
when 'M'
tagName1, tagName2, tagname3
when 'Y'
tagName1, tagName2, tagname3
But it didn't worked....
Below is the code that I wrote, while I play it only once.
Any advice, please..
DECLARE tagList varchar(255) DEFAULT 'tagName1,tagName2,tagName3';
DECLARE tagTypeList varchar(150) DEFAULT 'H,D,M,Y';
WHILE tagTypeList != '' DO
WHILE tagList != '' DO
SET tagNameArray = SUBSTRING_INDEX(tagList, ',', 1);
SET tagTypeArray = SUBSTRING_INDEX(tagTypeList, ',', 1);
IF(tagTypeArray = 'H') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 HOUR)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = (SELECT DATE_FORMAT(aDate,'%d'));
SET ago_H = (SELECT DATE_FORMAT(aDate,'%H'));
SET ago_W = (SELECT DATE_FORMAT(aDate,'%w'));
ELSEIF(tagTypeArray = 'D') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 DAY)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = (SELECT DATE_FORMAT(aDate,'%d'));
SET ago_H = 0;
SET ago_W = 0;
ELSEIF(tagTypeArray = 'M') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 MONTH)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = (SELECT DATE_FORMAT(aDate,'%m'));
SET ago_D = 0;
SET ago_H = 0;
SET ago_W = 0;
ELSEIF(tagTypeArray = 'Y') THEN
SET aDate = (SELECT (DATE_ADD(nDateTime, INTERVAL -1 YEAR)));
SET ago_Y = (SELECT DATE_FORMAT(aDate,'%Y'));
SET ago_M = 0;
SET ago_D = 0;
SET ago_H = 0;
SET ago_W = 0;
END IF;
SET selectValue = (SELECT tagvalue FROM datasource WHERE tagname = tagNameArray and tagtype = tagTypeArray and y=ago_Y and m=ago_M and d=ago_D and h=ago_H);
IF(selectValue IS NULL OR selectValue = '')
THEN
SET old_Value_3M = (Select LastValue from BwAnalogTable where TagName = tagNameArray and LogDate >= ago_3M order by LogDate desc, LogTime desc limit 1);
# Here Insert Querty
END IF;
IF LOCATE(',', tagList) > 0 THEN
SET tagList = SUBSTRING(tagList, LOCATE(',', tagList) + 1);
ELSE
SET tagList = '';
END IF;
END WHILE;
IF LOCATE(',', tagTypeList) > 0 THEN
SET tagTypeList = SUBSTRING(tagTypeList, LOCATE(',', tagTypeList) + 1);
ELSE
SET tagTypeList = '';
END IF;
END WHILE;
I have modified the code as shown below.
DECLARE done INT DEFAULT FALSE;
DECLARE tagType2 VARCHAR(255) DEFAULT '';
DECLARE tagName2 VARCHAR(255) DEFAULT '';
DECLARE tagType_Cur CURSOR for select tagType from tbtagtype;
DECLARE tagName_Cur CURSOR for select tagName from tbtaglist;
OPEN tagType_Cur;
LOOP1: LOOP
FETCH tagType_Cur INTO tagType2;
IF done THEN
CLOSE tagType_Cur;
LEAVE LOOP1;
END IF;
########## here insert your core query ###############
OPEN tagName_Cur;
LOOP2: LOOP
FETCH tagName_Cur INTO tagName2;
IF done THEN
CLOSE tagName_Cur;
SET done = FALSE;
LEAVE LOOP2;
END IF;
########## here insert your core query ###############
END LOOP LOOP2;
END LOOP LOOP1;

Rewrite MySQL Trigger to Postgres

guys!
I have a trigger in MySQL database:
CREATE DEFINER="root"#"127.0.0.1" TRIGGER `tai_actions_for_active_count` AFTER INSERT ON `actions` FOR EACH ROW BEGIN
DECLARE l_isnn TINYTEXT;
IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN
SET l_isnn = IF(NEW.isnn is NULL, '*', NEW.isnn);
IF NOT NEW.action_type = 'CLOSE' THEN
INSERT INTO subscriptions.`statistics_active_count`(`service_id`, `operator_id`, `isnn`, `active_count`)
VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1)
ON DUPLICATE KEY UPDATE active_count = active_count + 1;
ELSE
SET #tai_actions_for_active_count = -1;
UPDATE subscriptions.`statistics_active_count` SET active_count = #tai_actions_for_active_count := active_count - 1
WHERE `service_id` = NEW.service_id AND `operator_id` = NEW.operator_id AND `isnn` = l_isnn;
IF #tai_actions_for_active_count = 0 THEN DELETE FROM subscriptions.`statistics_active_count` WHERE `active_count` = 0; END IF;
END IF;
END IF;
END
So I need to rewrite it to make it works in Postgres database. As there's ON DUPLICATE KEY UPDATE I'm using Postgres version 9.5 with UPSERT (ON CONFLICT (KEY) DO UPDATE).
So I poorly know SQL language can you tell me what I'm doing wrong? There's the Postgres PL code:
DECLARE
l_isnn TEXT;
tai_actions_for_active_count INTEGER;
BEGIN
IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN
IF NEW.isnn is NULL THEN
l_isnn := '*';
ELSE
l_isnn := NEW.isnn;
END IF;
IF NOT NEW.action_type = 'CLOSE' THEN
INSERT INTO "subscriptions.statistics_active_count"(service_id, operator_id, isnn, active_count)
VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1)
ON CONFLICT(active_count) DO UPDATE SET active_count = active_count + 1;
ELSE
tai_actions_for_active_count := -1;
UPDATE "subscriptions.statistics_active_count" SET active_count = active_count - 1
-- (tai_actions_for_active_count := active_count - 1)
WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn;
UPDATE "subscriptions.statistics_active_count" SET tai_actions_for_active_count = active_count
WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn;
IF tai_actions_for_active_count = 0 THEN DELETE FROM "subscriptions.statistics_active_count" WHERE active_count = 0; END IF;
END IF;
END IF;
RETURN NULL;
END;
As I want to test this trigger I'm getting an error -- relation "subscriptions.statistics_active_count" does not exist
Can you help me with that code?
Finally I've got the solution. I guess :)
BEGIN
IF NEW.action_type IN ('CREATION', 'VERIFICATION', 'CLOSE') THEN
IF NEW.isnn IS NULL THEN
l_isnn := '*';
ELSE
l_isnn := NEW.isnn;
END IF;
IF NOT NEW.action_type = 'CLOSE' THEN
BEGIN
INSERT INTO subscriptions.statistics_active_count (service_id, operator_id, isnn, active_count)
VALUES (NEW.service_id, NEW.operator_id, l_isnn, 1);
EXCEPTION WHEN unique_violation THEN
UPDATE subscriptions.statistics_active_count SET active_count = active_count + 1
WHERE service_id = NEW.service_id and operator_id=NEW.operator_id;
END;
ELSE
tai_actions_for_active_count := -1;
WITH upd AS
(UPDATE subscriptions.statistics_active_count
SET active_count = active_count - 1
WHERE service_id = NEW.service_id AND operator_id = NEW.operator_id AND isnn = l_isnn;
RETURNING active_count)
SELECT *
FROM upd INTO tai_actions_for_active_count;
IF tai_actions_for_active_count = 0 THEN
DELETE FROM public.statistics_active_count
WHERE active_count = 0;
END IF;
END IF;
END IF;
END;

How to get data from table to variable with select in event?

I have the event
CREATE EVENT `start_insert_record_to_inout` ON SCHEDULE EVERY 10 SECOND STARTS '2014-07-12 12:07:00'
ON COMPLETION PRESERVE
ENABLE
COMMENT 'comment'
DO BEGIN
DECLARE `_count` INT DEFAULT 0;
DECLARE `_done` INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = 1;
SELECT `count` INTO `_count`
FROM state_execution
WHERE name = 'insert_record_to_inout' AND `type` = 'event'
LIMIT 1;
-- AND `type` = 'event';
IF _done THEN
INSERT INTO state_execution (`name`, `type`, `isUsed`,`count`) VALUES ('insert_record_to_inout', 'event','0',0);
END IF;
IF `_count` < 50 THEN
IF _done THEN
SET `_count` = 1;
SET _done = 0;
ELSE
SET `_count` = `_count` + 1;
END IF;
UPDATE state_execution SET `count` = `_count`
WHERE name = 'insert_record_to_inout' AND `type` = 'event';
call insert_record_to_inout();
SELECT `count` INTO `_count`
FROM state_execution
WHERE name = 'insert_record_to_inout' AND `type` = 'event'
LIMIT 1;
IF _done THEN
SET `_count` = 0;
ELSE
SET `_count` = `_count` - 1;
END IF;
UPDATE state_execution SET `count` = `_count` WHERE name = 'insert_record_to_inout' AND `type` = 'event';
END IF;
END
But this code
SELECT `count` INTO `_count`
FROM state_execution
WHERE name = 'insert_record_to_inout' AND `type` = 'event'
LIMIT 1;
not working. Please help me, thanks.

Creating function error sql server 2008

I want to create a fucntion, but getting error.
below is query:
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS TABLE
AS BEGIN
DECLARE
#TIMER_START_ACTIVITY_ID INT,
#TIMER_START_ACTIVITY_COMPLETED_ON DATETIME,
#TIMER_END_ACTIVITY_ID INT,
#TIMER_END_ACTIVITY_COMPLETED_ON DATETIME,
#SLA_TIME_SCHEDULE_IN_DAYS INT,
#SLA_DISPLAY VARCHAR(20),
#START_DATE DATETIME,
#END_DATE DATETIME,
#BUSINESS_START_TIME VARCHAR(10),
#BUSINESS_END_TIME VARCHAR(10),
#BUSINESS_HOURS INT,
#SLA_CUT_OFF_TIME VARCHAR(10),
#IS_OBJECT_STATUS_IS_TERMINAL INT,
#COMPLETED_ACTION_ID INT,
#UNCHECKED_ACTION_ID INT,
#DAY_ADDED INT
SELECT #IS_OBJECT_STATUS_IS_TERMINAL = CASE when wos.FLG_STATUS_TYPE = 'W' THEN 0 ELSE 1 END
FROM WF.WF_OBJECT_INSTANCE woi
INNER JOIN WF.WF_OBJECT_STATUS wos ON wos.OBJECT_STATUS_ID = woi.OBJECT_STATUS_ID
WHERE woi.LINK_PK_ID = #OBJECT_PK_ID
SET #SLA_TIME_SCHEDULE_IN_DAYS = (SELECT CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN lr.RUSH_NO_OF_DAYS ELSE s.NUM_OF_DAYS END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #SLA_DISPLAY = (SELECT
CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN s.DISPLAY_NAME + ' (' + CAST(lr.RUSH_NO_OF_DAYS AS VARCHAR) + ')' ELSE s.DISPLAY_NAME END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #BUSINESS_START_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_START_TIME')
SET #BUSINESS_END_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_END_TIME')
SET #BUSINESS_HOURS = (SELECT CAST(DATEDIFF(hour, CAST(#BUSINESS_START_TIME AS DATETIME), CAST(#BUSINESS_END_TIME AS DATETIME)) AS INT))
SET #SLA_CUT_OFF_TIME = (SELECT DATEPART(hour, CAST(s.CONFIG_VALUE AS TIME)) FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'SLA_CUT_OFF_TIME')
SET #COMPLETED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_COMPLETED')
SET #UNCHECKED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_UNCHECKED')
--GET SLA TIMER ACTIVITY IDs
SELECT #TIMER_START_ACTIVITY_ID = t.START_ACTIVITY_ID,
#TIMER_END_ACTIVITY_ID = t.END_ACTIVITY_ID
FROM [WF].WF_TIMER t
WHERE t.NAME = 'SLA_TIMER'
--Get START ACTIVITY ON
SELECT #TIMER_START_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
--AND
----{
--0 = ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
-- FROM WF.WF_OBJECT_ACTIVITY_HISTORY
-- WHERE LINK_PK_ID = #OBJECT_PK_ID
-- AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
-- AND ACTION_ID = #COMPLETED_ACTION_ID
-- ORDER BY ACTION_ON DESC), 0)
----}
ORDER BY ACTION_ON DESC
--Get END ACTIVITY ON
SELECT #TIMER_END_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
ORDER BY ACTION_ON DESC
--TO DO
--SET #TIMER_START_ACTIVITY_COMPLETED_ON = '2014-05-15 02:40:21.100'
--SET #TIMER_END_ACTIVITY_COMPLETED_ON = '2014-05-14 12:40:21.100'
SET #START_DATE = #TIMER_START_ACTIVITY_COMPLETED_ON
SET #DAY_ADDED = #SLA_TIME_SCHEDULE_IN_DAYS -- SLA Schedule Days
+ CASE WHEN DATEPART(hour, #TIMER_START_ACTIVITY_COMPLETED_ON) >= #SLA_CUT_OFF_TIME THEN 0 ELSE -1 END -- SLA Cut Off Time
SET #END_DATE = #START_DATE + #DAY_ADDED
--Exclud Holidays
--{
DECLARE #START_ON_DATE DATETIME = CAST(#START_DATE AS DATE)
WHILE #DAY_ADDED > 0
BEGIN
SELECT #END_DATE = #START_ON_DATE + #DAY_ADDED
--COUNT NO OF HOLIDAYS IF FALLING WITHIN START-DATE AND END-DATE
SELECT #DAY_ADDED = COUNT(*) FROM [WF].WF_CALENDAR WC --HOLIDAY LIST
WHERE WC.DATE BETWEEN #START_ON_DATE+1 AND #END_DATE AND (WC.IS_WEEKEND = 1 OR WC.IS_HOLIDAY = 1)
SET #START_ON_DATE = #END_DATE
END
--}
SET #END_DATE = (CAST(CAST(CAST(#END_DATE AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME))
;WITH TIMER_CTE AS (
SELECT #START_DATE AS OBJECT_CREATED_ON,
#END_DATE AS OBJECT_END_ON,
DIFFERENCE_IN_DAYS = DATEDIFF(dd, GETDATE(), #END_DATE),
TODAY_REMAINING_MINUTES =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))
ELSE 0 END,
TODAY_REMAINING_HOURS =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN (DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))/60)
ELSE 0 END
)
RETURN (
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY,
SLA_DUE = CONVERT(VARCHAR(10), CONVERT(DATETIME, tc.OBJECT_END_ON, 1), 101),
#BUSINESS_END_TIME AS BUSINESS_END_TIME,
SLA_START_ACTIVITY_CHECKED_ON = tc.OBJECT_CREATED_ON,
SLA_END_ACTIVITY_CHECKED_ON = #TIMER_END_ACTIVITY_COMPLETED_ON,
SLA_MISSED = CASE WHEN
--TODAY_REMAINING_MINUTES <= 0
--AND CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
--OR
( GETDATE()> #END_DATE)
OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 'Missed' ELSE NULL END,
tc.TODAY_REMAINING_HOURS,
tc.TODAY_REMAINING_MINUTES,
LAST_DAY_TIME_REMAINING =
CASE
WHEN #TIMER_END_ACTIVITY_COMPLETED_ON <= #END_DATE THEN 'Successful Completed'
WHEN CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
THEN
CASE WHEN
tc.TODAY_REMAINING_HOURS <=0 AND tc.TODAY_REMAINING_MINUTES > 0 THEN
CASE WHEN tc.TODAY_REMAINING_MINUTES = 1 THEN CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' min remaining'
ELSE CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' mins remaining' END
WHEN tc.TODAY_REMAINING_HOURS =1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hour remaining'
WHEN tc.TODAY_REMAINING_HOURS >1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hours remaining'
ELSE NULL
END
ELSE NULL
END,
REMAINING_DAYS = CASE WHEN tc.DIFFERENCE_IN_DAYS <=0 THEN '0 day'
WHEN tc.DIFFERENCE_IN_DAYS > 1 THEN CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' days '
ELSE CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' day ' END
FROM TIMER_CTE tc
)
END;
GO
I am getting this error:
Msg 156, Level 15, State 1, Procedure WFSlaTimer, Line 144
Incorrect syntax near the keyword 'RETURN'.
Msg 178, Level 15, State 1, Procedure WFSlaTimer, Line 144
A RETURN statement with a return value cannot be used in this context.
Msg 102, Level 15, State 31, Procedure WFSlaTimer, Line 189
Incorrect syntax near 'BEGIN'.
Any help please
There are two kind of function that return table. the inline function and multi-statement function. Yours is multi-statement. Here is the syntax for this:
--Transact-SQL Multistatement Table-valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name
( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ = default ] [READONLY] }
[ ,...n ]
]
)
RETURNS #return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[ ; ]
For more information refer to CREATE FUNCTION (Transact-SQL) BOL documentation.
You have to define the returned table's structure (fields and data types)
1) Add a variable name to the function definition (#tableVariable in the above example).
2) Fill the table definition (columns and datatypes)
3) Modify your function to insert the result into the defined table variable, then use an empty RETURN statement when the function should return.
1st step
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS #tableVariable TABLE (
IS_SHOW_SLA INT,
StartDate DATETIME2,
EndDate DATETIME2
/** List all of your returned columns like when you creating a table **/
)
AS
BEGIN
/** Do your stuff **/
INSERT INTO #tableVariable ( /* field list */) VALUES (/* value list */)
-- OR --
INSERT INTO #tableVariable ( /* field list */)
SELECT /* FieldList */ FROM myCTE
RETURN
END
2nd step
Modify your RETURN () statement like this:
INSERT INTO #tableVanriable (IS_SHOW_SLA , StartDate , EndDate)
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY
/** .... **/
FROM TIMER_CTE tc
/** 3rd step **/
RETURN