I am executing a stored procedure im MYSQL. That will generate 6000 records and insert that 6000 records into a Table. For this, that stored procedure is taking more than 45 min.The file size of stored procedure is 45kb. Systems RAM is 0.98GB.
Does system RAM affecting the stored procedure performance?
CREATE DEFINER=`root`#`localhost` PROCEDURE `sample`()
BEGIN
Declare FY_LHS Varchar(20);
Declare FY_RHS Varchar(20);
Declare abc int default 0;
Declare bcd varchar(40) default null;
Declare cde int default 0;
Declare def varchar(40) default null;
Declare efg int default 0;
Declare ghi varchar(40) default null;
Declare ijk varchar(40) default null;
Declare hij varchar(40) default null;
Declare ijk varchar(40) default null;
Declare param_month int ;
Declare monthsortsequence int default 0;
Declare p int default 0;
Declare q int default 0;
Declare r int default 0;
Declare s int default 0;
Declare t int default 0;
DECLARE done INT DEFAULT FALSE;
declare dateofdisch int default 0;
Declare fId int default 0;
DECLARE fac_cur CURSOR FOR SELECT r FROM u ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET param_month = Month(CURDATE());
IF param_month = 4 THEN SET monthsortsequence = 1;
ELSEIF param_month = 5 THEN SET monthsortsequence = 2;
ELSEIF param_month = 6 THEN SET monthsortsequence = 3;
ELSEIF param_month = 7 THEN SET monthsortsequence = 4;
ELSEIF param_month = 8 THEN SET monthsortsequence = 5;
ELSEIF param_month = 9 THEN SET monthsortsequence = 6;
ELSEIF param_month = 10 THEN SET monthsortsequence = 7;
ELSEIF param_month = 11 THEN SET monthsortsequence = 8;
ELSEIF param_month = 12 THEN SET monthsortsequence = 9;
ELSEIF param_month = 1 THEN SET monthsortsequence = 10;
ELSEIF param_month = 2 THEN SET monthsortsequence = 11;
ELSEIF param_month = 3 THEN SET monthsortsequence = 12;
END IF;
OPEN fac_cur;
read_loop: LOOP
FETCH fac_cur INTO fId;
IF fId >= 65 THEN
LEAVE read_loop;
END IF;
IF fId != 0 THEN
IF MONTH(CURDATE())>=4 THEN
Set FY_LHS = YEAR(CURDATE());
Set FY_RHS = YEAR(CURDATE())+1;
ELSE
Set FY_LHS = YEAR(CURDATE())-1;
Set FY_RHS = YEAR(CURDATE());
END IF;
Select tblbc.StateId, tblst.StateName, tblbc.DistrictId,
tblst.District, tblbc.kID, tblst.k, tblbc.FacilityName, tblbc.FacilityType,
tblbc.ReportingToId
into abc, bcd, cde, def, efg, ghi, ijk, hij, ijk
from u tblbc inner join tblstateinfo tblst on
tblbc.stateid = tblst.stateid and tblbc.DistrictId = tblst.dcode and tblbc.kID = tblst.tcode
where tblbc.r = fId;
Delete from data where Year = concat(FY_LHS,'-',FY_RHS) and Month = param_month and r = fId;
Set p = (select count(*) as Count from w tblreg inner join tblp1s tblu on tblreg.p1id = tblu.p1id where tblreg.pm = 0 and (Str_To_Date(tblreg.ty, '%d/%m/%Y') between Str_To_Date(concat(FY_LHS,'/04/01'), '%Y/%m/%d') and Str_To_Date(concat(FY_RHS,'/03/31'), '%Y/%m/%d')) and month(Str_To_Date(tblreg.ty, '%d/%m/%Y')) = param_month and tblu.r = fId);
Set q = (Select count(ytid) as Count From w reg inner join tblp1s tblu on reg.p1id = tblu.p1Id where datediff(CurDate(), Str_To_Date(reg.LMP, '%d/%m/%Y')) < 300 and reg.pm = 0 and (Str_To_Date(reg.ty, '%d/%m/%Y') between Str_To_Date(concat(FY_LHS,'/04/01'), '%Y/%m/%d') and Str_To_Date(concat(FY_RHS,'/03/31'), '%Y/%m/%d')) and month(Str_To_Date(reg.ty, '%d/%m/%Y')) = param_month and tblu.r = fId);
Set r = (Select count(reg.ytid) from (Select ts.p1id, ts.ytid, count(ts.ytid) as count from tblhjlist ts where ts.fgtype = 'ANC' and ts.actualdateofaction is not null and (Str_To_Date(actualdateofaction, '%d/%m/%Y') between Str_To_Date(concat(FY_LHS,'/04/01'), '%Y/%m/%d') and Str_To_Date(concat(FY_RHS,'/03/31'), '%Y/%m/%d')) and month(Str_To_Date(actualdateofaction, '%d/%m/%Y')) = param_month group by ts.ytid, ts.p1id) tss left join w reg on tss.ytid = reg.ytid inner join tblp1s tblu on reg.p1Id = tblu.p1id where tss.count = 3 and tblu.r = fId);
Set s = (Select count(sl.ytid) from (Select p1id, ytid from tblhjlist where fgid = 1 and fgtype = 'FT' and actualdateofaction is not null and (Str_To_Date(actualdateofaction, '%d/%m/%Y') between Str_To_Date(concat(FY_LHS,'/04/01'), '%Y/%m/%d') and Str_To_Date(concat(FY_RHS,'/03/31'), '%Y/%m/%d')) and month(Str_To_Date(actualdateofaction, '%d/%m/%Y')) = param_month) sl inner join w reg on sl.ytid = reg.ytid inner join tblp1s tblu on reg.p1id = tblu.p1id and reg.pm = 0 and tblu.r = fId);
Set t = (Select count(ts.ytid) from (Select p1id, ytid from tblhjlist where ((fgtype = 'FT' and fgid = 2) or (fgtype = 'FTBooster' and fgid = 3)) and actualdateofaction is not null and (Str_To_Date(actualdateofaction, '%d/%m/%Y') between Str_To_Date(concat(FY_LHS,'/04/01'), '%Y/%m/%d') and Str_To_Date(concat(FY_RHS,'/03/31'), '%Y/%m/%d')) and month(Str_To_Date(actualdateofaction, '%d/%m/%Y')) = 9 group by ytid) ts inner join w reg on ts.ytid = reg.ytid inner join tblp1s tblu on reg.p1Id = tblu.p1Id and reg.pm = 0 and tblu.r = fId);
.
.
.
.
.
40 queries
insert into data (year, month, stateId, state, districtId, district, kid, k, facilityname, facilityType, sortsequenceMonth, r, sortsequence, itemRefno, itemvalue, ReportingToId) values (concat(FY_LHS,'-',FY_RHS), param_month, abc, bcd, cde, def, efg, ghi, ijk, hij, monthsortsequence, fId, 2, '1.1.1', q, ijk);
insert into data (year, month, stateId, state, districtId, district, kid, k, facilityname, facilityType, sortsequenceMonth, r, sortsequence, itemRefno, itemvalue, ReportingToId) values (concat(FY_LHS,'-',FY_RHS), param_month, abc, bcd, cde, def, efg, ghi, ijk, hij, monthsortsequence, fId, 1, '1.1', p, ijk);
insert into data (year, month, stateId, state, districtId, district, kid, k, facilityname, facilityType, sortsequenceMonth, r, sortsequence, itemRefno, itemvalue, ReportingToId) values (concat(FY_LHS,'-',FY_RHS), param_month, abc, bcd, cde, def, efg, ghi, ijk, hij, monthsortsequence, fId, 3, '1.3', r, ijk);
insert into data (year, month, stateId, state, districtId, district, kid, k, facilityname, facilityType, sortsequenceMonth, r, sortsequence, itemRefno, itemvalue, ReportingToId) values (concat(FY_LHS,'-',FY_RHS), param_month, abc, bcd, cde, def, efg, ghi, ijk, hij, monthsortsequence, fId, 4, '1.4.1', s, ijk);
insert into data (year, month, stateId, state, districtId, district, kid, k, facilityname, facilityType, sortsequenceMonth, r, sortsequence, itemRefno, itemvalue, ReportingToId) values (concat(FY_LHS,'-',FY_RHS), param_month, abc, bcd, cde, def, efg, ghi, ijk, hij, monthsortsequence, fId, 5, '1.4.2', t, ijk);
.
.
.
.
40 insert statements
set fId = fId + 1;
END IF;
END LOOP;
CLOSE fac_cur;
END
You need to check which statement exactly in the stored procedure
is taking time by adding some debug points (ex: You can insert
timestamp after each select into some temp table).
You need to check that you have proper indexes on table for select
queries.
Related
i have SP for update the data into new data with this query, so basically every id have own value for own rule_id, and this SP is to update the data with the new one from the SP
CREATE DEFINER=`root`#`localhost` PROCEDURE `update_discount_campaign_advanced2`(IN DiscountCampaignId INT(10),
IN rule_percentage VARCHAR(255),
IN rule_quota_daily_max VARCHAR(255),
IN rule_discount_daily VARCHAR(255),
IN rule_discount_weekly VARCHAR (255),
IN rule_discount_monthly VARCHAR(255),
IN rule_spesific_payment_method VARCHAR(255),
IN rule_spesific_cc_operator VARCHAR(255),
IN allow_other_product VARCHAR(255)
)
proc:
BEGIN
DECLARE is_discount_campaign_id INT(10);
DECLARE is_rule_percentage VARCHAR(255);
DECLARE is_rule_quota_daily_max VARCHAR(255);
DECLARE is_rule_discount_daily VARCHAR(255);
DECLARE is_rule_discount_weekly VARCHAR(255);
DECLARE is_rule_discount_monthly VARCHAR(255);
DECLARE is_rule_spesific_payment_method VARCHAR(255);
DECLARE is_rule_spesific_cc_operator VARCHAR(255);
DECLARE is_allow_other_product VARCHAR(255);
DECLARE param_1_message TEXT;
SET #is_discount_campaign_id = DiscountCampaignId;
SET #is_rule_percentage = rule_percentage;
SET #is_rule_quota_daily_max = rule_quota_daily_max;
SET #is_rule_discount_daily = rule_discount_daily;
SET #is_rule_discount_weekly = rule_discount_weekly;
SET #is_rule_discount_monthly = rule_discount_monthly;
SET #is_rule_spesific_payment_method = rule_spesific_payment_method;
SET #is_rule_spesific_cc_operator = rule_spesific_cc_operator;
SET #is_allow_other_product = allow_other_product;
SELECT CONVERT( CONCAT('Maaf, ID discount_campaign tidak bisa \'0\'') USING UTF8) INTO param_1_message;
IF (DiscountCampaignId = 0) THEN
SELECT param_1_message AS message;
LEAVE proc;
END IF;
IF (DiscountCampaignId != 0) THEN
INSERT INTO discount_campaign_advanced (id,discount_campaign_id,
discount_advanced_rules_id, value, createdAt, status, updatedAt)
select *, CASE WHEN
unitData.id is NULL THEN NULL ELSE NOW() END as updatedAt from (SELECT dca.id , DiscountCampaignId, dar.id as dar_id1, CASE WHEN dar.id = 1
THEN #is_rule_percentage WHEN dar.id = 2 THEN #is_rule_quota_daily_max
WHEN dar.id = 3 THEN #is_rule_discount_daily WHEN dar.id = 4
THEN #is_rule_discount_weekly WHEN dar.id = 5 THEN #is_rule_discount_monthly
WHEN dar.id = 6 THEN #is_rule_spesific_payment_method WHEN dar.id = 7
THEN #is_rule_spesific_cc_operator END, coalesce(dca.createdAt, NOW()), CASE when (dar.id = 1
and #is_rule_percentage != '0') THEN 1 WHEN (dar.id = 2 and
#is_rule_quota_daily_max != '0') THEN 1 WHEN
(dar.id = 3 and #is_rule_discount_daily != '0') THEN 1 WHEN (dar.id = 4 and
#is_rule_discount_weekly != '0') THEN 1
WHEN (dar.id = 5 AND #is_rule_discount_monthly != '0') THEN 1 WHEN (dar.id = 6
AND #is_rule_spesific_payment_method != '0')
THEN 1 WHEN (dar.id = 7 AND #is_rule_spesific_cc_operator != '0') THEN 1 ELSE 0 END as bb
FROM
discount_advanced_rules dar
LEFT JOIN
discount_campaign_advanced dca ON dca.discount_advanced_rules_id = dar.id
and dca.discount_campaign_id = DiscountCampaignId) as unitData
WHERE unitData.bb = 1
UNION
SELECT dca.id, DiscountCampaignId, dca.discount_advanced_rules_id, CASE WHEN dca.discount_advanced_rules_id = 1
THEN #is_rule_percentage WHEN dca.discount_advanced_rules_id = 2 THEN #is_rule_quota_daily_max
WHEN dca.discount_advanced_rules_id = 3 THEN #is_rule_discount_daily WHEN dca.discount_advanced_rules_id = 4
THEN #is_rule_discount_weekly WHEN dca.discount_advanced_rules_id = 5 THEN #is_rule_discount_monthly
WHEN dca.discount_advanced_rules_id = 6 THEN #is_rule_spesific_payment_method WHEN dca.discount_advanced_rules_id = 7
THEN #is_rule_spesific_cc_operator END, coalesce(dca.createdAt, NOW()), CASE when (dca.discount_advanced_rules_id = 1
and #is_rule_percentage != '0') THEN 1 WHEN (dca.discount_advanced_rules_id = 2 and
#is_rule_quota_daily_max != '0') THEN 1 WHEN
(dca.discount_advanced_rules_id = 3 and #is_rule_discount_daily != '0')
THEN 1 WHEN (dca.discount_advanced_rules_id = 4 and
#is_rule_discount_weekly != '0') THEN 1
WHEN (dca.discount_advanced_rules_id = 5
AND #is_rule_discount_monthly != '0') THEN 1 WHEN (dca.discount_advanced_rules_id = 6
AND #is_rule_spesific_payment_method != '0')
THEN 1 WHEN (dca.discount_advanced_rules_id = 7 AND #is_rule_spesific_cc_operator != '0') THEN 1 ELSE 0 END as bb,
NOW()
FROM discount_campaign_advanced dca
WHERE dca.discount_campaign_id = DiscountCampaignId
on duplicate key update id = values(id), discount_campaign_id = values(discount_campaign_id),
discount_advanced_rules_id = values(discount_advanced_rules_id), value = values(value),
createdAt = values(createdAt), status = values(status), updatedAt = values(updatedAt);
END IF;
IF (allow_other_product != 0) THEN
INSERT INTO discount_campaign_advanced (id,discount_campaign_id,
discount_advanced_rules_id, value, createdAt, status, updatedAt)
select *, CASE WHEN
unitData.id is NULL THEN NULL ELSE NOW() END as updatedAt from (SELECT dca.id , DiscountCampaignId, dar.id as dar_id1, CASE WHEN dar.id = 8
THEN #is_allow_other_product END, coalesce(dca.createdAt, NOW()), CASE when (dar.id = 8
and #is_allow_other_product != '0') THEN 1 ELSE 0 END as bb
FROM
discount_advanced_rules dar
LEFT JOIN
discount_campaign_advanced dca ON dca.discount_advanced_rules_id = dar.id
and dca.discount_campaign_id = DiscountCampaignId) as unitData
WHERE unitData.bb = 1
UNION
SELECT dca.id, DiscountCampaignId, dca.discount_advanced_rules_id, CASE WHEN dca.discount_advanced_rules_id = 8 THEN #is_allow_other_product END, coalesce(dca.createdAt, NOW()), CASE when (dca.discount_advanced_rules_id = 8
and #is_allow_other_product != '0') THEN 1 ELSE 0 END as bb,
NOW()
FROM discount_campaign_advanced dca
WHERE dca.discount_campaign_id = DiscountCampaignId
on duplicate key update id = values(id), discount_campaign_id = values(discount_campaign_id),
discount_advanced_rules_id = values(discount_advanced_rules_id), value = values(value),
createdAt = values(createdAt), status = values(status), updatedAt = values(updatedAt);
END IF;
END
but idk why when i call this SP call brambang_uom.update_discount_campaign_advanced2(2757, '5', '5', '1', '1', '1', '1', '1', '9');
it returns Error Code: 1048. Column 'value' cannot be null`, where my wrong at?
I got this error message:
Result consisted of more than one row
but I check my procedure again and again but I cannot find any problem:
DROP PROCEDURE IF EXISTS SP_Fetch_Returned_With_Serials;
CREATE PROCEDURE `SP_Fetch_Returned_With_Serials`()
BEGIN
DECLARE Num BIGINT UNSIGNED DEFAULT 0;
DECLARE __Product_Id bigint UNSIGNED DEFAULT NULL;
DECLARE __Serials varchar(255) DEFAULT NULL;
DECLARE done INT DEFAULT 0;
DECLARE cur CURSOR FOR
SELECT product_id, serials FROM tmp_table_returned_product_serial;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
START TRANSACTION ;
SET #Document_Id = 0 ;
SET #Product_Id = 0;
SET #Payment_Amount = 0;
OPEN cur;
read_loop:
LOOP
IF done
THEN
LEAVE read_loop;
END IF;
FETCH cur INTO __Product_Id,__Serials;
CALL SP_Separate_Numeric_Values(`__Serials`);
SET #Is_Returnable = 0;
SET #Level_Id = 0;
SET #Free_Day = 0;
SET #Penalty_Percent = 0;
SET #Factor_Type_Id = 0;
SET #Currency_Id = 0;
SET #Customer_Id = 0;
SET #Factor_Id = 0;
SET #Value = 0;
SET #Real_Fee = 0;
SET #Date_At = CURRENT_DATE();
SET #Diff_Days = 0;
SET #New_Factor_Id = 0;
SET #New_Detail_Factor_Id = 0;
SET #Receipt_Remit_Type_Id = 0;
SET #Return_Penalty_Percent = 0;
SET #Return_Penalty_Price = 0;
SET #Document_Number = 0;
SELECT id INTO #Factor_Type_Id FROM Tb_Factor_Types WHERE name = 'back_sale_factor';
SELECT COUNT(NV.Number) INTO #Value FROM Numeric_Values NV;
SELECT TP.is_returnable,
TU.level_id,
currency_id,
customer_id,
VF.id,
VF.product_id,
real_fee,
date_at
INTO #Is_Returnable,#Level_Id,#Currency_Id,#Customer_Id,#Factor_Id,#Product_Id,#Real_Fee,#Date_At
FROM Vw_Factor_Master_Details VF
INNER JOIN Tb_Factor_Detail_Serials TFDS ON TFDS.detail_id = VF.detail_id
INNER JOIN Tb_Products TP ON VF.product_id = TP.id
INNER JOIN Tb_Users TU ON TU.user_id = VF.customer_id
INNER JOIN Numeric_Values NV ON NV.Number = TFDS.serial_id;
IF (#Is_Returnable)
THEN
SET #Product_Title = '';
SET #Error_Msg = '';
SELECT IFNULL(TPT.title, TP.title_en) AS title INTO #Product_Title FROM Tb_Products TP
LEFT JOIN (SELECT title, product_id FROM Tb_Product_Translations WHERE locale = #Locale) TPT
ON TP.id = TPT.product_id WHERE product_id = #Product_Id;
SELECT message INTO #Error_Msg FROM Tb_Errors WHERE error_code = 1000028 AND locale = #Locale;
SET #Error_Msg = REPLACE(#Error_Msg, ':product', #Product_Title);
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = #Error_Msg;
END IF;
SELECT DATEDIFF(CURRENT_DATE(), #Date_At) INTO #Diff_Days;
SELECT MAX(`number`) INTO Num FROM Tb_Factors WHERE year_id = #Fiscal_Year AND type = 'sale_factor';
SET Num = ifnull(Num, 0) + 1;
SELECT JSON_EXTRACT(JSON_EXTRACT(TS.value, CONCAT('$.', #Level_Id)), '$.free_day')
INTO #Free_Day
FROM Tb_Settings TS
WHERE `key` = 'returned_product';
SELECT JSON_EXTRACT(JSON_EXTRACT(TS.value, CONCAT('$.', #Level_Id)), '$.penalty_percent')
INTO #Penalty_Percent
FROM Tb_Settings TS
WHERE `key` = 'returned_product';
IF (#Diff_Days > #Free_Day)
THEN
SET #Payment_Amount = #Payment_Amount + ((#Real_Fee - (#Real_Fee * #Penalty_Percent / 100)) * #Value);
SET #Return_Penalty_Percent = #Penalty_Percent;
SET #Return_Penalty_Price = #Real_Fee * #Penalty_Percent / 100;
END IF;
IF(#New_Factor_Id = 0)
THEN
INSERT INTO Tb_Factors (type, sale_place, product_type, company_id, branch_id, cash_desk_id, type_id, year_id,
currency_id, finaler_id, signature_id, customer_id, final_at, signature_at,
reference_factor_id, creator_id, number)
VALUES ('sale_factor', 'branch', 'product', #Company, #Branch_Id, NULL, #Factor_Type_Id, #Fiscal_Year,
#Currency_Id, #Auth_User, #Auth_User, #Customer_Id, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP(),
#Factor_Id, #Auth_User, Num);
SET #New_Factor_Id = LAST_INSERT_ID();
END IF;
INSERT INTO Tb_Factor_Details (product_id, value, real_fee, fee, factor_id, creator_id, return_penalty_percent,
return_penalty_price)
VALUES (#Product_Id, #Value, #Real_Fee, #Real_Fee, #New_Factor_Id, #Auth_User, #Penalty_Percent,
#Return_Penalty_Price);
SET #New_Detail_Factor_Id = LAST_INSERT_ID();
INSERT INTO Tb_Factor_Detail_Serials (serial_id, detail_id)
SELECT NV.Number, #New_Detail_Factor_Id FROM Numeric_Values NV;
SELECT id INTO #Receipt_Remit_Type_Id FROM Tb_Receipt_Remit_Types WHERE name = 'return_of_sales';
SET #Warehouse_Id = 0;
SELECT id INTO #Warehouse_Id FROM Tb_Warehouses WHERE warehouse_branch_id = #Branch_Id LIMIT 1;
IF(#Document_Id = 0)
THEN
SELECT document_number
FROM Tb_Documents
WHERE fiscal_year_id = #Fiscal_Year
ORDER BY document_number DESC
LIMIT 1
INTO #Document_Number;
SET #Document_Number = #Document_Number + 1;
INSERT INTO Tb_Documents (type, factor_id, warehouse_id, receipt_remit_type_id, fiscal_year_id, document_number,
creator_id)
VALUES ('receipt', #New_Factor_Id, #Warehouse_Id, #Receipt_Remit_Type_Id, #Fiscal_Year, #Document_Number,
#Auth_User);
SET #Document_Id = LAST_INSERT_ID();
END IF;
INSERT INTO Tb_Document_Details (product_id, value, confirmed_at, confirmed_by, creator_id, document_id)
VALUES (#Product_Id, #Value, CURRENT_TIMESTAMP(), #Auth_User, #Auth_User, #Document_Id);
SET #Document_Detail_Id = LAST_INSERT_ID();
INSERT INTO Tb_Detail_Serial_Numbers (serial_number_id, detail_id, origin_cost_center_id, confirmed_at,
confirmed_by)
SELECT NV.Number, #Document_Detail_Id,NULL,CURRENT_TIMESTAMP(),#Auth_User FROM Numeric_Values NV;
END LOOP;
CLOSE cur;
SET #Type_Id = 0;
SELECT id INTO #Type_Id FROM Tb_Payment_Types WHERE name = 'cash' LIMIT 1;
INSERT INTO Tb_Receive_Payment (model_type, model_id, factor_id, type_id, receive_amount, payment_amount,year_id,creator_id)
VALUES ('cashdesk', NULL, #New_Factor_Id, #Type_Id, 0, #Payment_Amount,#Fiscal_Year,#Auth_User);
SET #Payment_Id = LAST_INSERT_ID();
SELECT #Factor_Id as factor_id,#Payment_Id as payment_id,#Payment_Amount as payment_amount;
COMMIT;
END
I've got a SQL query that when I run it in SQL Server Mgmt Studio takes 15 seconds to complete. When I translate it to linq and run it in LINQPad it takes 1:50 to complete. Have I just completely bungled the "translation" to linq?
This is the SQL:
WITH details AS (
SELECT DISTINCT SerialNumber, OrgLevel3, OrgLevel4, [Status Label]
FROM vw_PSM_AssetIntransit
WHERE yyyyww = DATENAME(yy, GETDATE()) + RIGHT('00' + DATENAME(wk, GETDATE()), 2) AND pro_status <> 'retired'
)
SELECT OrgLevel3, OrgLevel4, COUNT(DISTINCT SerialNumber) Total,
SUM(CASE WHEN [Status Label] NOT IN ('15-21 Days InTransit', '8-14 Days InTransit', 'over 21 Days InTransit') THEN 1 ELSE 0 END) Compliant
FROM details
GROUP BY OrgLevel3, OrgLevel4
ORDER BY 1, 2
and this is the LINQ I translated it to:
var now = DateTime.Now;
var dtf = System.Globalization.DateTimeFormatInfo.CurrentInfo;
var calendar = dtf.Calendar;
var yearWW = now.Year * 100 + calendar.GetWeekOfYear(now, dtf.CalendarWeekRule, dtf.FirstDayOfWeek);
var badStatusLabels = new string[] { "15-21 Days InTransit", "8-14 Days InTransit", "over 21 Days InTransit" };
var details = (
from r in Vw_PSM_AssetIntransit
where r.yyyyww == yearWW && r.Pro_status != "retired"
select new { r.SerialNumber, r.OrgLevel3, r.OrgLevel4, r.StatusLabel }
).Distinct();
var data = from r in details
group r by new { r.OrgLevel3, r.OrgLevel4 } into grp
orderby grp.Key.OrgLevel3, grp.Key.OrgLevel4
select new
{
OrgLevel3 = grp.Key.OrgLevel3,
OrgLevel4 = grp.Key.OrgLevel4,
Total = grp.Select(x => x.SerialNumber).Distinct().Count(),
Compliant = grp.Sum(x => !badStatusLabels.Contains(x.StatusLabel) ? 1 : 0)
};
Console.WriteLine(data);
This is what LINQPad shows the SQL query came out as:
-- Region Parameters
DECLARE #p0 Int = 201816
DECLARE #p1 NVarChar(1000) = 'retired'
DECLARE #p2 NVarChar(1000) = '15-21 Days InTransit'
DECLARE #p3 NVarChar(1000) = '8-14 Days InTransit'
DECLARE #p4 NVarChar(1000) = 'over 21 Days InTransit'
DECLARE #p5 Int = 1
DECLARE #p6 Int = 0
-- EndRegion
SELECT [t3].[OrgLevel3], [t3].[OrgLevel4], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t5].[SerialNumber]
FROM (
SELECT DISTINCT [t4].[SerialNumber], [t4].[OrgLevel3], [t4].[OrgLevel4], [t4].[Status Label]
FROM [vw_PSM_AssetIntransit] AS [t4]
WHERE ([t4].[yyyyww] = #p0) AND ([t4].[pro_status] <> #p1)
) AS [t5]
WHERE ((([t3].[OrgLevel3] IS NULL) AND ([t5].[OrgLevel3] IS NULL)) OR (([t3].[OrgLevel3] IS NOT NULL) AND ([t5].[OrgLevel3] IS NOT NULL) AND ((([t3].[OrgLevel3] IS NULL) AND ([t5].[OrgLevel3] IS NULL)) OR (([t3].[OrgLevel3] IS NOT NULL) AND ([t5].[OrgLevel3] IS NOT NULL) AND ([t3].[OrgLevel3] = [t5].[OrgLevel3]))))) AND ((([t3].[OrgLevel4] IS NULL) AND ([t5].[OrgLevel4] IS NULL)) OR (([t3].[OrgLevel4] IS NOT NULL) AND ([t5].[OrgLevel4] IS NOT NULL) AND ((([t3].[OrgLevel4] IS NULL) AND ([t5].[OrgLevel4] IS NULL)) OR (([t3].[OrgLevel4] IS NOT NULL) AND ([t5].[OrgLevel4] IS NOT NULL) AND ([t3].[OrgLevel4] = [t5].[OrgLevel4])))))
) AS [t6]
) AS [Total], [t3].[value] AS [Compliant]
FROM (
SELECT SUM([t2].[value]) AS [value], [t2].[OrgLevel3], [t2].[OrgLevel4]
FROM (
SELECT
(CASE
WHEN NOT ([t1].[Status Label] IN (#p2, #p3, #p4)) THEN #p5
ELSE #p6
END) AS [value], [t1].[OrgLevel3], [t1].[OrgLevel4]
FROM (
SELECT DISTINCT [t0].[SerialNumber], [t0].[OrgLevel3], [t0].[OrgLevel4], [t0].[Status Label]
FROM [vw_PSM_AssetIntransit] AS [t0]
WHERE ([t0].[yyyyww] = #p0) AND ([t0].[pro_status] <> #p1)
) AS [t1]
) AS [t2]
GROUP BY [t2].[OrgLevel3], [t2].[OrgLevel4]
) AS [t3]
ORDER BY [t3].[OrgLevel3], [t3].[OrgLevel4]
I am trying to create stored procedure and getting error:
Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right
syntax to use near 'DECLARE #LoopCounter INT DEFAULT 0; DECLARE
#MaxId INT DEFAULT 0; DECLARE ' at line 21
DELIMITER $$
USE dollar$$
DROP PROCEDURE IF EXISTS sp_get_products_google_feed$$
CREATE DEFINER=root#localhost PROCEDURE sp_get_products_google_feed()
BEGIN
DROP TABLE IF EXISTS tmp_Product_List;
CREATE TEMPORARY TABLE tmp_Product_List(
SELECT DISTINCT p.products_id AS PID, p.products_model AS ID, pd.products_name AS Title, pd.products_description AS Description,
'' AS Google_product_category, '' AS product_type, p.products_model AS link, p.products_image AS Image_link,
'new' AS Condition1, 'in stock' AS Availability, p.products_price AS Price, '' AS Sale_Price, '' AS Sale_price_effective_date,
p.products_upc AS GTin, p.manufacturers_id, '' AS MPN, '' AS Item_group_id, '' AS Gender, '' AS Age_group, '' AS Color, '' AS Size,
'Free' AS Shipping, '' AS Shipping_Weight
FROM
zc_products_to_categories pc, zc_products p, zc_products_description pd WHERE
pc.categories_id IN
(SELECT DISTINCT mg.sub_category_id AS id FROM tbl_map_google_category_master mg WHERE mg.category_id = 1
UNION
SELECT DISTINCT mg.sub_sub_category_id AS id FROM tbl_map_google_category_master mg WHERE mg.category_id = 1
ORDER BY id) AND
p.products_id = pc.products_id AND
p.products_id = pd.products_id AND
p.products_status = 1 ORDER BY PID);
DECLARE #LoopCounter INT DEFAULT 0;
DECLARE #MaxId INT DEFAULT 0;
DECLARE #GoogleCategoryid INT DEFAULT 0;
SELECT #LoopCounter = MIN(PID), #MaxId = MAX(PID) FROM tmp_Product_List;
WHILE (#LoopCounter IS NOT NULL AND #LoopCounter <= #MaxId)
BEGIN
SELECT #GoogleCategoryid = google_category_id FROM tbl_map_google_category_master
WHERE
category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) OR
sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) OR
sub_sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) LIMIT 0,1;
UPDATE tmp_Product_List SET Google_product_category = #GoogleCategoryid WHERE products_id = #LoopCounter;
SET #LoopCounter = #LoopCounter + 1
IF(##ROWCOUNT = 0 )
BEGIN
SET #LoopCounter = #LoopCounter + 1
CONTINUE
END
END
SELECT * FROM tmp_Product_List;
END$$
DELIMITER ;
But if I remove below code from script, it run successfully. Trying to find error in full script but no luck.
DECLARE #LoopCounter INT DEFAULT 0;
DECLARE #MaxId INT DEFAULT 0;
DECLARE #GoogleCategoryid INT DEFAULT 0;
SELECT #LoopCounter = MIN(PID), #MaxId = MAX(PID) FROM tmp_Product_List;
WHILE (#LoopCounter IS NOT NULL AND #LoopCounter <= #MaxId)
BEGIN
SELECT #GoogleCategoryid = google_category_id FROM tbl_map_google_category_master
WHERE
category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) OR
sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) OR
sub_sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = #LoopCounter) LIMIT 0,1;
UPDATE tmp_Product_List SET Google_product_category = #GoogleCategoryid WHERE products_id = #LoopCounter;
SET #LoopCounter = #LoopCounter + 1
IF(##ROWCOUNT = 0 )
BEGIN
SET #LoopCounter = #LoopCounter + 1
CONTINUE
END
END
You had a few issues that I've worked through.
The first is the declaring of the variables with an # sign before them, I've removed those.
The second was in the WHILE ... BEGIN ... END. The syntax is WHILE ... DO ... END WHILE.
The third is a missing semi-colon just before the IF(##ROWCOUNT).
The last one that I haven't fixed below is the use of ##ROWCOUNT. ##ROWCOUNT isn't a variable in MySQL. You can find alternatives here
DELIMITER $$
USE dollar$$
DROP PROCEDURE IF EXISTS sp_get_products_google_feed$$
CREATE DEFINER=root#localhost PROCEDURE sp_get_products_google_feed()
BEGIN
DECLARE LoopCounter INT DEFAULT 0;
DECLARE MaxId INT DEFAULT 0;
DECLARE GoogleCategoryid INT DEFAULT 0;
DROP TABLE IF EXISTS tmp_Product_List;
CREATE TEMPORARY TABLE tmp_Product_List(
SELECT DISTINCT p.products_id AS PID, p.products_model AS ID, pd.products_name AS Title, pd.products_description AS Description,
'' AS Google_product_category, '' AS product_type, p.products_model AS link, p.products_image AS Image_link,
'new' AS Condition1, 'in stock' AS Availability, p.products_price AS Price, '' AS Sale_Price, '' AS Sale_price_effective_date,
p.products_upc AS GTin, p.manufacturers_id, '' AS MPN, '' AS Item_group_id, '' AS Gender, '' AS Age_group, '' AS Color, '' AS Size,
'Free' AS Shipping, '' AS Shipping_Weight
FROM
zc_products_to_categories pc, zc_products p, zc_products_description pd WHERE
pc.categories_id IN
(SELECT DISTINCT mg.sub_category_id AS id FROM tbl_map_google_category_master mg WHERE mg.category_id = 1
UNION
SELECT DISTINCT mg.sub_sub_category_id AS id FROM tbl_map_google_category_master mg WHERE mg.category_id = 1
ORDER BY id) AND
p.products_id = pc.products_id AND
p.products_id = pd.products_id AND
p.products_status = 1 ORDER BY PID);
SELECT LoopCounter = MIN(PID), MaxId = MAX(PID) FROM tmp_Product_List;
WHILE (LoopCounter IS NOT NULL AND LoopCounter <= MaxId)
DO
SELECT GoogleCategoryid = google_category_id FROM tbl_map_google_category_master
WHERE
category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = LoopCounter) OR
sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = LoopCounter) OR
sub_sub_category_id = (SELECT MAX(categories_id) FROM zc_products_to_categories WHERE products_id = LoopCounter) LIMIT 0,1;
UPDATE tmp_Product_List SET Google_product_category = GoogleCategoryid WHERE products_id = LoopCounter;
SET LoopCounter = LoopCounter + 1;
IF(##ROWCOUNT = 0 )
BEGIN
SET LoopCounter = LoopCounter + 1
CONTINUE
END
END WHILE
SELECT * FROM tmp_Product_List;
END$$
DELIMITER ;
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