MySQL Store Procedure Error Code: 1064 - mysql

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 ;

Related

Result consisted of more than one row - Procedure

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

How to fix sintax o procedure MySQL with variables?

I have the following body of procedure, that I can not save cause Mysql sintax error:
BEGIN
DECLARE v_user_id INT;
DECLARE v_order_id INT;
DECLARE v_min_price INT;
UPDATE ordersperformers SET ordersperformers.Status = 1
WHERE EXISTS (
SELECT
MIN(ordersperformers.DeliveryPrice + ordersperformers.Price), ordersperformers.Users_Id,
ordersperformers.Orders_Id
INTO v_min_price, v_user_id, v_order_id
FROM ordersperformers
INNER JOIN
orders ON orders.Id = ordersperformers.Orders_Id WHERE
NOW() >= DATE_SUB(orders.DeliveryDate, INTERVAL 2 HOUR) AND orders.Status = 0 AND ordersperformers.Status = 0
) AND ordersperformers.Orders_Id = v_order_id AND ordersperformers.Users_Id = v_user_id;
END
It tells that problem near INTO:
Reading proposed solution, query can be simplified with JOIN clause and reduced WHERE condition:
UPDATE ordersperformers op
INNER JOIN orders o ON op.Orders_Id = o.Id
SET op.Status = 1
WHERE DATE_SUB(o.DeliveryDate, INTERVAL 2 HOUR) <= NOW()
AND o.Status = 0 AND op.Status = 0
I tested some ways, and have found working sintax, tha fixed my issue:
BEGIN
DECLARE v_user_id INT DEFAULT 0;
DECLARE v_order_id INT DEFAULT 0;
DECLARE v_min_price INT DEFAULT 0;
UPDATE ordersperformers SET ordersperformers.Status = 1
WHERE EXISTS (
SELECT
MIN(ordersperformers.DeliveryPrice + ordersperformers.Price) = #v_min_price, ordersperformers.Users_Id = #v_user_id,
ordersperformers.Orders_Id = #v_order_id
FROM ordersperformers
INNER JOIN
orders ON orders.Id = ordersperformers.Orders_Id WHERE
NOW() >= DATE_SUB(orders.DeliveryDate, INTERVAL 2 HOUR) AND orders.Status = 0 AND ordersperformers.Status = 0
) AND ordersperformers.Orders_Id = v_order_id AND ordersperformers.Users_Id = v_user_id;
END

Stored Procedure is taking more time to execute

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.

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;

Any other way to perform joins on same column?

I was just rewriting my question as this answer wont work for me. I have a stored procedure as follows:
--GetAllFilteredProjects
Alter PROCEDURE [GetAllFilteredProjects]
#UserId Int,
#ServerGroupId int,
#ProjectIDs UDT_ProjectIDs Readonly,
#ProjectDesc NVARCHAR(2000),
#TopRecords INT,
#StartProjectID INT,
#CustomerGroupId INT,
#SearchStates dbo.[UDT_SearchStates] Readonly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #StartProjectNumber INT
DECLARE #AcceptUnAcceptFilterNumberv INT
DECLARE #IgnoreRestrictedNumberv INT
DECLARE #SearchProjectIDsCount INT
DECLARE #SearchProjectDesc VARCHAR
SET #IgnoreRestrictedNumberv=0
SET #AcceptUnAcceptFilterNumberv =0
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('StartProjectIDFilter')
where USERID = #UserId
SET #ProjectDesc = REPLACE(#ProjectDesc, '*', '%')
SET #ProjectDesc = REPLACE(#ProjectDesc, '?', '_')
Print(#ProjectDesc)
Select #SearchProjectIDsCount=count(*) from #ProjectIDs;
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept','ProjectFilterAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1)
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterAccept')
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 0
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1) -- UnAccepted
BEGIN
SET #AcceptUnAcceptFilterNumberv = 3
END
END
END
select #IgnoreRestrictedNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterIgnoreRestricted')
where USERID = #UserId
IF OBJECT_ID('TEMPDB..#PROJECTS') IS NOT NULL DROP TABLE #PROJECTS
CREATE TABLE #PROJECTS
(
TMP_PROJECT_ID INT,
TMP_SERVERGROUP_ID INT,
TMP_DESCRIPTION NVARCHAR(1000),
TMP_PROJECT_STATE_ID INT,
TMP_ACCEPTED_STATE_ID INT,
TMP_ISRESTRICTED_ID INT
)
IF OBJECT_ID('TEMPDB..#SELECTED_STATES') IS NOT NULL DROP TABLE #SELECTED_STATES
CREATE TABLE #SELECTED_STATES
(
TMP_PREFSET_STATEID INT
)
-- All the project accepted for server group and unaccepted for server group which are promoted to
-- Validation or Pilot or Factory states
IF #IgnoreRestrictedNumberv=1
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
AND p.IsRestricted = 0
END
ELSE
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
END
-- State selected by user to filter the projects
INSERT INTO #SELECTED_STATES
select ap.AFPStateId
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
inner join AFPState ap on 'ProjectFilter' + ap.AFPStateDesc = PropertyName
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 1 -- Accepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM, #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT #PROJECTS.TMP_PROJECT_ID
FROM #PROJECTS
GROUP BY #PROJECTS.TMP_PROJECT_ID HAVING MAX(#PROJECTS.TMP_ACCEPTED_STATE_ID) IN
--WHERE #PROJECTS.TMP_ACCEPTED_STATE_ID IN
(
SELECT #SELECTED_STATES.TMP_PREFSET_STATEID
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 2 -- Both
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case
when [1]=2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID in
(
SELECT DISTINCT PJ.TMP_PROJECT_ID
FROM #PROJECTS PJ
--WHERE isnull(PJ.TMP_ACCEPTED_STATE_ID,0) <=
GROUP BY PJ.TMP_PROJECT_ID HAVING MAX(isnull(PJ.TMP_ACCEPTED_STATE_ID,0)) <=
(
SELECT max(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 3 -- UnAccepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT p.TMP_PROJECT_ID
FROM #PROJECTS p
WHERE (SELECT max(ISNULL(PJ.TMP_ACCEPTED_STATE_ID,0))
FROM #PROJECTS PJ
GROUP BY PJ.TMP_PROJECT_ID HAVING PJ.TMP_PROJECT_ID = p.TMP_PROJECT_ID
) <
(
SELECT MAX(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
END
Now while inserting values into my table projects I have a condition where p.IsRestrictedID=0.
Here I have one more thing which I need to consider. I need to insert the projects which have IsRestricted=1 where this could be executed when this statement returns 1
SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId
Means I need to consider the project which has IsRestricted=1 when the above select query returns 1.
I wanted to add this to that Insert into project query.
How can I do that?
Just add the prefix of the table alias every place you use the column name, to prevent the ambiguous column error:
SELECT
p.projectid,
pa.servergroupid, -- Here I added "pa." as a prefix
p.description,
. . .
I got the solution for this I just need to add an OR condition while inserting Projects.
The modified one is as follows:
--GetAllFilteredProjects
Alter PROCEDURE [GetAllFilteredProjects]
#UserId Int,
#ServerGroupId int,
#ProjectIDs UDT_ProjectIDs Readonly,
#ProjectDesc NVARCHAR(2000),
#TopRecords INT,
#StartProjectID INT,
#CustomerGroupId INT,
#SearchStates dbo.[UDT_SearchStates] Readonly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #StartProjectNumber INT
DECLARE #AcceptUnAcceptFilterNumberv INT
DECLARE #IgnoreRestrictedNumberv INT
DECLARE #SearchProjectIDsCount INT
DECLARE #SearchProjectDesc VARCHAR
SET #IgnoreRestrictedNumberv=0
SET #AcceptUnAcceptFilterNumberv =0
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('StartProjectIDFilter')
where USERID = #UserId
SET #ProjectDesc = REPLACE(#ProjectDesc, '*', '%')
SET #ProjectDesc = REPLACE(#ProjectDesc, '?', '_')
Print(#ProjectDesc)
Select #SearchProjectIDsCount=count(*) from #ProjectIDs;
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept','ProjectFilterAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1)
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterAccept')
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 0
BEGIN
select #AcceptUnAcceptFilterNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterUnAccept')
where USERID = #UserId
IF(#AcceptUnAcceptFilterNumberv = 1) -- UnAccepted
BEGIN
SET #AcceptUnAcceptFilterNumberv = 3
END
END
END
select #IgnoreRestrictedNumberv = COUNT(PropertyName)
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
and PropertyName in('ProjectFilterIgnoreRestricted')
where USERID = #UserId
IF OBJECT_ID('TEMPDB..#PROJECTS') IS NOT NULL DROP TABLE #PROJECTS
CREATE TABLE #PROJECTS
(
TMP_PROJECT_ID INT,
TMP_SERVERGROUP_ID INT,
TMP_DESCRIPTION NVARCHAR(1000),
TMP_PROJECT_STATE_ID INT,
TMP_ACCEPTED_STATE_ID INT,
TMP_ISRESTRICTED_ID INT
)
IF OBJECT_ID('TEMPDB..#SELECTED_STATES') IS NOT NULL DROP TABLE #SELECTED_STATES
CREATE TABLE #SELECTED_STATES
(
TMP_PREFSET_STATEID INT
)
-- All the project accepted for server group and unaccepted for server group which are promoted to
-- Validation or Pilot or Factory states
IF #IgnoreRestrictedNumberv=1
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid, servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
AND p.IsRestricted = 0
OR p.IsRestricted IN (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = p.projectid AND PR.ServerGroupId = #ServerGroupId )
END
ELSE
BEGIN
INSERT INTO #PROJECTS
SELECT p.projectid,servergroupid,p.description,p.StateId AS ProjectState, pa.stateid ,p.IsRestricted
FROM v_Project p left outer join ProjectAcception pa ON p.ProjectId = pa.ProjectId and pa.ServerGroupId=#ServerGroupId
WHERE P.CustomerGroupId = #CustomerGroupId AND P.StateId IN(Select StateID From #SearchStates) and P.StateId in (select ss.AFPStateId from ServerGroupStateSettings ss where ss.servergroupid=#ServerGroupId)
--added by shankar, regarding the filtering functionality
--in projects tab of a server group
and (#SearchProjectIDsCount =0 Or p.projectid in
(1673))
AND (Upper(p.Description) LIKE '%' +Upper(#ProjectDesc) + '%')
AND p.projectid>=#StartProjectID
END
-- State selected by user to filter the projects
INSERT INTO #SELECTED_STATES
select ap.AFPStateId
from UserPreferenceSet u inner join PreferenceSet p on u.PreferenceID=p.ID
inner join AFPState ap on 'ProjectFilter' + ap.AFPStateDesc = PropertyName
where USERID = #UserId
IF #AcceptUnAcceptFilterNumberv = 1 -- Accepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM, #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT #PROJECTS.TMP_PROJECT_ID
FROM #PROJECTS
GROUP BY #PROJECTS.TMP_PROJECT_ID HAVING MAX(#PROJECTS.TMP_ACCEPTED_STATE_ID) IN
--WHERE #PROJECTS.TMP_ACCEPTED_STATE_ID IN
(
SELECT #SELECTED_STATES.TMP_PREFSET_STATEID
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 2 -- Both
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case
when [1]=2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID in
(
SELECT DISTINCT PJ.TMP_PROJECT_ID
FROM #PROJECTS PJ
--WHERE isnull(PJ.TMP_ACCEPTED_STATE_ID,0) <=
GROUP BY PJ.TMP_PROJECT_ID HAVING MAX(isnull(PJ.TMP_ACCEPTED_STATE_ID,0)) <=
(
SELECT max(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
ELSE IF #AcceptUnAcceptFilterNumberv = 3 -- UnAccepted
BEGIN
SELECT TOP(#TopRecords) TMP_PROJECT_ID AS ProjectId,TMP_SERVERGROUP_ID as ServerGroupId,TMP_DESCRIPTION as Description,
(case
when TMP_PROJECT_STATE_ID = 1 then 'Development'
when TMP_PROJECT_STATE_ID = 2 then 'Validation'
when TMP_PROJECT_STATE_ID = 3 then 'Pilot'
when TMP_PROJECT_STATE_ID = 4 then 'Factory'
end) as State,
(case [1] when 2 then 1
else 0
end) as Validation,
(case
when [1] = 3 then 1
when [2] = 3 then 1
else 0
end) as Pilot,
(case
when [1] = 4 then 1
when [2] = 4 then 1
when [3] = 4 then 1
else 0
end) as Factory,PL.LockedBy,PA.CreatedBy,
(CASE
WHEN TMP_ISRESTRICTED_ID = 0 THEN 1
ELSE (SELECT COUNT(*) FROM dbo.ProjectRestriction PR WHERE PR.ProjectId = TMP_PROJECT_ID AND PR.ServerGroupId = #ServerGroupId )
END
)AS IsUnRestrictedServerGroup
FROM (
SELECT #PROJECTS.TMP_PROJECT_ID,
#PROJECTS.TMP_DESCRIPTION,
#PROJECTS.TMP_SERVERGROUP_ID,
#PROJECTS.TMP_PROJECT_STATE_ID,
#PROJECTS.TMP_ACCEPTED_STATE_ID , row_number() OVER(PARTITION BY #PROJECTS.TMP_PROJECT_ID, #PROJECTS.TMP_SERVERGROUP_ID ORDER BY #PROJECTS.TMP_ACCEPTED_STATE_ID ASC) as ROWNUM , #PROJECTS.TMP_ISRESTRICTED_ID
FROM #PROJECTS
WHERE #PROJECTS.TMP_PROJECT_ID IN
(
SELECT DISTINCT p.TMP_PROJECT_ID
FROM #PROJECTS p
WHERE (SELECT max(ISNULL(PJ.TMP_ACCEPTED_STATE_ID,0))
FROM #PROJECTS PJ
GROUP BY PJ.TMP_PROJECT_ID HAVING PJ.TMP_PROJECT_ID = p.TMP_PROJECT_ID
) <
(
SELECT MAX(#SELECTED_STATES.TMP_PREFSET_STATEID)
FROM #SELECTED_STATES
)
)
) A
PIVOT
(
MAX(TMP_ACCEPTED_STATE_ID)
FOR ROWNUM IN ([1],[2],[3],[4])
)B
LEFT JOIN dbo.ProjectLock PL ON PL.ProjectID=TMP_PROJECT_ID
LEFT JOIN dbo.ProjectAutomaticAcceptance PA ON PA.ProjectID=TMP_PROJECT_ID
END
END