Related
I want to force a user's string input in a stored procedure to uppercase. I tried writing UPPER prior to the #parameterName but I got a syntax error. Is this possible? Would be it be better suited to convert the string to uppercase in the statement itself? Here's the code to my SP where I was attempting to use UPPER in the parameter definition.
ALTER PROCEDURE [dbo].[UpdateEntries]
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
#CLASS_TYPE_ID INT,
#ENTRY_PRICE DEC(4,2),
#ENTRY_DESCRIPT NVARCHAR(max),
#PET_FRIENDLY BIT,
#AGE_RESTRICTION BIT,
#PRICE_RANGE_ID INT,
#RESTAURANT_TYPE_ID INT NULL
AS
BEGIN
SET NOCOUNT ON;
IF #ENTRY_TYPE = 'ACTIVITY'
BEGIN
UPDATE ACTIVITY_DETAIL
SET ACT_NAME = #ENTRY_NAME,
ACT_PRICE = #ENTRY_PRICE,
ACT_DESCRIPT = #ENTRY_DESCRIPT,
ACT_DOG_FRIENDLY = #PET_FRIENDLY,
ACT_AGE_RESTRICTION = #AGE_RESTRICTION,
ACT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[ACTIVITY_DETAIL] WHERE ACT_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'BUSINESS'
BEGIN
UPDATE BUSINESS_DETAIL
SET BUSINESS_NAME = #ENTRY_NAME,
BUSINESS_PRICE = #ENTRY_PRICE,
BUSINESS_DESCRIPT = #ENTRY_DESCRIPT,
BUSINESS_DOG_FRIENDLY = #PET_FRIENDLY,
BUSINESS_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[BUSINESS_DETAIL] WHERE BUSINESS_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'HOTEL'
BEGIN
UPDATE HOTEL_DETAIL
SET HOTEL_NAME = #ENTRY_NAME,
HOTEL_PRICE = #ENTRY_PRICE,
HOTEL_DESCRIPT = #ENTRY_DESCRIPT,
HOTEL_PET_FRIENDLY = #PET_FRIENDLY,
HOTEL_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[HOTEL_DETAIL] WHERE HOTEL_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'RESTAURANT'
BEGIN
UPDATE RESTAURANT_DETAIL
SET RESTAURANT_NAME = #ENTRY_NAME,
RESTAURANT_PRICE_AVG = #ENTRY_PRICE,
RESTAURANT_DESCRIPT = #ENTRY_DESCRIPT,
RESTAURANT_DOG_FRIENDLY = #PET_FRIENDLY,
RESTAURANT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[RESTAURANT_DETAIL] WHERE RESTAURANT_NAME = #ENTRY_NAME);
END
END
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
These are wrong. No such usage.
#ENTRY_TYPE NVARCHAR(20) = '',
#ENTRY_NAME NVARCHAR(50),
SELECT #ENTRY_TYPE = UPPER(#ENTRY_TYPE);
SELECT #ENTRY_NAME = UPPER(#ENTITY_NAME);
We have a Stored Procedure in SQL Server which expects datetime column to be in MMddyyyy format and results in error
Conversion failed when converting date and/or time from character string.
whenever the system calendar setting is set to ddMMyyyy format. The same SP works fine if other date format is set for the system such as dd-MMM-yyyy works fine and returns no error. SP throws error when the calender setting is changed to ddMMyyyy format. It will work fine for dates below 12 as it takes the first digits as month but fails when higher dates like 15 or 28 is given. I am trying to find a solution so that it will work for all calendar settings as I cannot restrict the end users from changing their calendar settings. Please help me ...
Here is my SP
CREATE PROCEDURE [dbo].[usp_704000]
-- Add the parameters for the stored procedure here
#Dt uttTrnBRS readonly,
#Dt1 uttTrnBRS1 readonly
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #RowStatus Int
Declare #TrnId Int
Declare #DocNo Varchar(15)
Declare #NextNo Int
Declare #Return SmallInt
Select #RowStatus = MAX(RowStatus), #Return = 0, #TrnId = 0
From #Dt T0
BEGIN TRANSACTION
--NEW Mode Handle the Insertion of New Records
IF (#RowStatus = 2)
BEGIN
BEGIN TRY
Insert into TrnBRS (CmpId, FinYear, FYPrd, DocId, SeriesId, DocDate, DocRef, DocStatus, BankCode, BankName, BankAcNo, AcId, AcCode,
AcDesc, BankAcId, EndDt, EndBalAmt, LastRcnDt, BalAmt, Diff, Remarks, BranchCode, BaseId, CUserId, CreateDt)
Select T0.CmpId, T2.FinYear, T2.FYPrdId FYPrd, T3.DocId, T0.SeriesId, Cast(T0.DocDate as Date) DocDate, T0.DocRef, '3' DocStatus,
T0.BankCode, T0.BankName, T0.BankAcNo, T0.AcId, T0.AcCode, T0.AcDesc, T0.BankAcId,
Cast(T0.EndDt as Date) EndDt, ISNULL(T0.EndBalAmt, 0) EndBalAmt, Cast(T0.LastRcnDt as Date) LastRcnDt, ISNULL(T0.BalAmt, 0) BalAmt, ISNULL(T0.Diff, 0) Diff,
T0.Remarks, T3.BranchCode, T3.BaseId, T0.CUserId, GetDate() CreateDt
From #Dt T0 Cross Join CmpMst T1
Left Join FYPrdMst T2 ON T0.DocDate Between T2.PrdFrom and T2.PrdTo
Inner Join (Select T0.DocId, T0.BaseId, T1.SeriesId, T1.SFinYear, T1.EFinYear, T0.BranchCode
From DocNum T0 Inner Join DocNum1 T1 ON T0.DocId = T1.DocId
Where T0.BaseId = 34) T3 ON T2.FinYear Between T3.SFinYear and ISNULL(T3.EFinYear, 3000)
Where T0.RowStatus = 2;
IF (##ERROR = 0)
SET #TrnId = ##IDENTITY;
IF (##ERROR = 0)
Insert into TrnBRS1 (TrnId, LineNum, BranchCode, PDocNo, PDocDate, PDocRef, PRefDate, DrAmtLC, CrAmtLC, Narration, ClearAmt, BankDt, PTrnId, PBaseId, PDocId,
JnlBaseId, JnlDocId, JnlDocNo, JnlTrnId, JnlLineNum, AdjEntry, Notes, RowIndex)
Select #TrnId TrnId, ROW_NUMBER() OVER (Order by T0.RowIndex) LineNum, T0.BranchCode, T0.PDocNo, Cast(T0.PDocDate as Date) PDocDate, T0.PDocRef,
Cast(T0.PRefDate as Date) PRefDate, T0.DrAmtLC, T0.CrAmtLC, T0.Narration, T0.ClearAmt, Cast(T0.BankDt as Date) BankDt, T0.PTrnId, T0.PBaseId, T0.PDocId,
T0.JnlBaseId, T0.JnlDocId, T0.JnlDocNo, T0.JnlTrnId, T0.JnlLineNum, T0.AdjEntry, T0.Notes, ROW_NUMBER() OVER (Order by T0.RowIndex) RowIndex
From #Dt1 T0
Where ISNULL(T0.IsCheck, 'N') = 'Y'; -- and ISDATE(CONVERT(Varchar(10), T0.BankDt, 111)) = 1;
IF (##ERROR = 0)
Insert into TrnBRS2 (TrnId, LineNum, BranchCode, PDocNo, PDocDate, PDocRef, PRefDate, DrAmtLC, CrAmtLC, Narration, PTrnId, PBaseId, PDocId,
JnlBaseId, JnlDocId, JnlDocNo, JnlTrnId, JnlLineNum, Notes, RowIndex)
Select #TrnId TrnId, ROW_NUMBER() OVER (Order by T0.RowIndex) LineNum, T0.BranchCode, T0.PDocNo, T0.PDocDate, T0.PDocRef,
T0.PRefDate, T0.DrAmtLC, T0.CrAmtLC, T0.Narration, T0.PTrnId, T0.PBaseId, T0.PDocId,
T0.JnlBaseId, T0.JnlDocId, T0.JnlDocNo, T0.JnlTrnId, T0.JnlLineNum, T0.Notes, ROW_NUMBER() OVER (Order by T0.RowIndex) RowIndex
From #Dt1 T0
Where ISNULL(T0.IsCheck, 'N') = 'N'; -- and ISDATE(CONVERT(Varchar(10), T0.BankDt, 111)) = 1;
IF (##ERROR = 0)
Update TrnJnl1
SET RecnDt = T1.BankDt,
RecnSys = 'Y', RecnTrnId = #TrnId, RecnType = 1
From TrnJnl1 T0 Inner Join TrnBRS1 T1 ON T0.TrnId = T1.JnlTrnId and T0.LineNum = T1.JnlLineNum and T1.TrnId = #TrnId;
IF (##ERROR = 0)
Select #NextNo = T1.NextNo + 1,
#DocNo = ISNULL(T1.Prefix, '') + REPLICATE('0', T1.NumLen-LEN(CAST(#NextNo as VARCHAR(5))))+CAST(#NextNo as VARCHAR(5)) +
ISNULL(T1.Suffix, '')
From TrnBRS T0 Inner Join DocNum1 T1 ON T0.DocId = T1.DocId and T0.SeriesId = T1.SeriesId
Where T0.TrnId = #TrnId
IF (##ERROR = 0)
Insert into BankMst3 (BankAcId, BRDate, AcId, BRAmtLC, CUserId, CreateDate)
Select T0.BankAcId, T0.EndDt, T0.AcId, T0.EndBalAmt, T0.CUserId, GetDate() CreateDate
From TrnBRS T0
Where T0.TrnId = #TrnId;
IF (##ERROR = 0)
Update DocNum1
SET NextNo = #NextNo
From DocNum1 T0 Inner Join TrnBRS T1 ON T0.DocID = T1.DocID and T0.SeriesId = T1.SeriesId and T1.TrnId = #TrnId
IF (##ERROR = 0)
Update TrnBRS SET DocNo = #DocNo Where TrnId = #TrnId
IF (##ERROR = 0)
BEGIN
COMMIT TRANSACTION;
Select 0 RetVal, #TrnId TrnId, 'Transaction Saved...' ErrMsg, 0 ErrType;
RETURN
END
END TRY
BEGIN CATCH
BEGIN
ROLLBACK TRANSACTION;
SELECT -1 RetVal, #TrnId TrnId, ERROR_MESSAGE() AS ErrMsg, 1 ErrType
RETURN
END
END CATCH
END
ELSE
BEGIN
BEGIN TRY
Insert into TrnBRS (CmpId, FinYear, FYPrd, DocId, SeriesId, DocDate, DocRef, DocStatus, CancelState, CanclTrnId, EndDt, EndBalAmt,
LastRcnDt, BalAmt, Diff, Remarks, BaseId, CUserId, CreateDt)
Select T0.CmpId, T0.FinYear, T0.FYPrd, T0.DocId, T0.SeriesId, T0.DocDate, T0.DocRef, '3' DocStatus, 'N' CancelState, T0.TrnId CanclTrnId,
T0.EndDt, ISNULL(T0.EndBalAmt, 0) EndBalAmt, T0.LastRcnDt, ISNULL(T0.BalAmt, 0) BalAmt, ISNULL(T0.Diff, 0) Diff,
T0.Remarks, T0.BaseId, T0.CUserId, GetDate() CreateDt
From TrnBRS T0 Inner Join #Dt T1 ON T0.TrnId = T1.TrnId
Where T1.RowStatus = 3;
SET #TrnId = ##IDENTITY;
Update TrnBRS
SET CancelState = 'Y', DocStatus = '4', CanclTrnId = #TrnId
From TrnBRS T0 Inner Join #Dt T1 ON T0.TrnId = T1.TrnId and T1.RowStatus = 3;
Insert into TrnBRS1 (TrnId, LineNum, BranchCode, PDocNo, PDocDate, PDocRef, PRefDate, DrAmtLC, CrAmtLC, Narration, ClearAmt,
BankDt, PTrnId, PBaseId, PDocId, JnlBaseId, JnlDocId, JnlDocNo, JnlTrnId, JnlLineNum, AdjEntry, Notes, RowIndex)
Select #TrnId TrnId, T0.LineNum, T0.BranchCode, T0.PDocNo, T0.PDocDate, T0.PDocRef, T0.PRefDate, T0.DrAmtLC, T0.CrAmtLC,
T0.Narration, T0.ClearAmt *-1, T0.BankDt, T0.PTrnId, T0.PBaseId, T0.PDocId, T0.JnlBaseId, T0.JnlDocId, T0.JnlDocNo,
T0.JnlTrnId, T0.JnlLineNum, T0.AdjEntry, T0.Notes, T0.RowIndex
From TrnBRS1 T0 Inner Join #Dt T1 ON T0.TrnId = T1.TrnId and T1.RowStatus = 3;
Update TrnJnl1
SET RecnDt = NULL, RecnSys = NULL, RecnTrnId = NULL, RecnType = NULL
From TrnJnl1 T0 Inner Join TrnBRS1 T1 ON T0.TrnId = T1.JnlTrnId and T0.LineNum = T1.JnlLineNum and T1.TrnId = #TrnId
Select #NextNo = T1.NextNo + 1,
#DocNo = ISNULL(T1.Prefix, '') +
Substring(Cast(Year(T0.DocDate) as VARCHAR(4)),3,2) + REPLICATE('0', T1.NumLen-LEN(CAST(#NextNo as VARCHAR(5))))+CAST(#NextNo as VARCHAR(5)) +
ISNULL(T1.Suffix, '')
From #Dt T0 Inner Join DocNum1 T1 ON T0.DocId = T1.DocId
Update DocNum1
SET NextNo = #NextNo
From DocNum1 T0 Inner Join #Dt T1 ON T0.DocID = T1.DocID
IF (##ERROR <> 0) RETURN ##ERROR
Update TrnBRS SET DocNo = #DocNo Where TrnId = #TrnId
IF (##ERROR <> 0) RETURN ##ERROR
BEGIN
COMMIT TRANSACTION;
Select 0 RetVal, #TrnId TrnId, 'Transaction Reversed...' ErrMsg, 0 ErrType;
RETURN
END
END TRY
BEGIN CATCH
BEGIN
ROLLBACK TRANSACTION
SELECT -1 RetVal, #TrnId TrnId, ERROR_MESSAGE() AS ErrMsg, 1 ErrType
RETURN
END
END CATCH
END
END
I had tried to convert the ddMMyyyy format(103) using the convert statement SELECT CONVERT(DATE, T1.BankDt, 103) instead of T1.BankDt(which is the datetime field we are trying to manipulate) but didn't succeed. It still throws error saying conversion failed for dates above 12 as it expects dates in MMddyyyy format
EDIT 2
Thank You all for the supports...
I had find the issue at last, the real issue was in another stored procedure which is used to populate the initial value in which the BankDt field was populated with '' empty string so that the field is treated as character string instead of date field. I had changed '' BankDt to Convert(Date,null,103) BankDt ... Now everything works fine
the real issue was in another stored procedure which is used to populate the initial value in which the BankDt field was populated with '' empty string so that the field is treated as character string instead of date field. I had changed
'' BankDt
to
Convert(Date,null,103) BankDt
... Now everything works fine
The following stored procedure works fine and returns data. However I wanted to also insert the data into a table for debugging before the final select. The code for the insert is commented out just before the final select. The insert uses the exact same select, without the order by, as the data source. However when I run the procedure with the insert uncommented I get an error:
Invalid Object Name BudgetSummaryDetail
I don't why using the object name is fine in the final select but if I try to use it for the insert I get an error. I'm sure there is a reason but I've tried it a bunch of different ways and I can't seem to figure it out. Any help or insight would be most appreciated.
ALTER PROCEDURE [dbo].[rptBudgetSummaryTest]
#Fy AS CHAR(4),
#Index_No AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#PCA AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#Appro_Sym AS VARCHAR(MAX) = NULL, -- "IN" - NULL for all; otherwise, comma seperated list of values
#IncludeNonFundedPositions AS BIT = 1,
#OnlyNonZeroPYs AS BIT = 0,
#OnlyNonZeroAllotment AS BIT = 0,
#mrgpcain as dbo.mrgpcain READONLY
AS
IF 1=0 BEGIN
SET FMTONLY OFF
END
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- SET XACT_ABORT ON causes the entire transaction to be
-- rolled back on a run-time error instead of just the sql
-- statement that caused the error.
SET XACT_ABORT ON
BEGIN
-- Tally tables for optional multi-value parameters
SELECT Item
INTO #Index_No_ParamValues
FROM [Common].dbo.Split(#Index_No, ',')
IF (SELECT COUNT(*) FROM #Index_No_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #Index_No_ParamValues
END
SELECT Item
INTO #PCA_ParamValues
FROM [Common].dbo.Split(#PCA, ',')
IF (SELECT COUNT(*) FROM #PCA_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #PCA_ParamValues
END
SELECT Item
INTO #Appro_Sym_ParamValues
FROM [Common].dbo.Split(#Appro_Sym, ',')
IF (SELECT COUNT(*) FROM #Appro_Sym_ParamValues WHERE Item IS NOT NULL) < 1
BEGIN
TRUNCATE TABLE #Appro_Sym_ParamValues
END
;WITH
BudgetSummaryDetail
AS (
SELECT
tblPCAIn.FY,
tblPCAIn.Index_No,
tblPCAIn.PCA,
tblPCAIn.Obj_Det,
tblPCAIn.Agy_Obj,
tblPCAIn.PYs,
Calc_PYs = IIF(((tblPCAIn.Obj_Det='427' AND tblPCAIn.Agy_Obj='04') OR tblPCAIn.Obj_Det='439') AND (CAST(tblPCAIn.PCA AS INT) BETWEEN 5000 AND 5999),
IIF(tblPCAFl.Fund_Src = 'F', (tblPCAIn.PYs * tblPCAFl.W_Pnct), 0),
(tblPCAIn.PYs * tblPCAFl.Pnct)),
Calc_Allot = IIF(((tblPCAIn.Obj_Det='427' AND tblPCAIn.Agy_Obj='04') OR tblPCAIn.Obj_Det='439') AND (CAST(tblPCAIn.PCA AS INT) BETWEEN 5000 AND 5999),
IIF(tblPCAFl.Fund_Src = 'F', (tblPCAIn.Allotment * tblPCAFl.W_Pnct), 0),
(tblPCAIn.Allotment * tblPCAFl.Pnct)),
tblPCAFl.Appro_Sym,
tblPCAFl.Fund_Src,
tblPCAFl.Fund_No,
tblPCAFl.Method,
tblPCAFl.Project,
PCT = ROUND(tblPCAFl.Pnct * 100, 0)
FROM
dbo.tblIndex AS tblIndex
INNER JOIN #mrgpcain AS tblPCAIn ON
tblPCAIn.FY = tblIndex.FY AND
tblPCAIn.Index_No = tblIndex.Index_No
INNER JOIN dbo.tblPCA AS tblPCA ON
tblPCA.FY = tblPCAIn.FY AND
tblPCA.PCA = tblPCAIn.PCA
INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
tblPCAFl.FY = tblPCA.FY AND
tblPCAFl.PCA = tblPCA.PCA
INNER JOIN dbo.tblAppro AS tblAppro ON
tblAppro.FY = tblPCAFl.FY AND
tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
LEFT JOIN #Index_No_ParamValues ON
tblIndex.Index_No = #Index_No_ParamValues.Item
LEFT JOIN #PCA_ParamValues ON
tblPCAIn.PCA = #PCA_ParamValues.Item
LEFT JOIN #Appro_Sym_ParamValues ON
tblAppro.Appro_Sym = #Appro_Sym_ParamValues.Item
WHERE
(#Index_No_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #Index_No_ParamValues)) AND
(#PCA_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #PCA_ParamValues)) AND
(#Appro_Sym_ParamValues.Item IS NOT NULL OR NOT EXISTS (SELECT TOP 1 Item FROM #Appro_Sym_ParamValues)) AND
(((#IncludeNonFundedPositions = 0) AND
(tblPCA.PCA <> '02727')
) OR (#IncludeNonFundedPositions = 1)) AND
(((#OnlyNonZeroPYs = 1) AND
(tblPCAIn.PYs <> 0.0)
) OR (#OnlyNonZeroPYs = 0)) AND
(((#OnlyNonZeroAllotment = 1) AND
(tblPCAIn.Allotment <> 0)
) OR (#OnlyNonZeroAllotment = 0))
)
--DELETE FROM tblBS_Test
--INSERT INTO tblBS_Test
--SELECT * FROM (
--SELECT
-- tblIndex.Dept_Id,
-- tblIndex.Dpty_Id,
-- tblIndex.Brch_Id,
-- tblIndex.Div_Id,
-- detail.Index_No,
-- tblIndex.Index_Title,
-- detail.PCA,
-- tblPCA.PCA_Title,
-- PROGLINK = REPLACE(tblPCA.Program+tblPCA.Element+tblPCA.Component+tblPCA.Task, '', '0'),
-- FUNDLINK = tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
-- tblAppro.Ref,
-- detail.Obj_Det,
-- detail.Agy_Obj,
-- PYs,
-- POS = IIF(((detail.Obj_Det = '003') AND (RTRIM(detail.Agy_Obj) = '')), detail.Calc_PYs, 0.0),
-- Calc_PYs = detail.Calc_PYs,
-- detail.Calc_Allot,
-- PCT
--FROM
-- BudgetSummaryDetail AS detail
-- INNER JOIN dbo.tblIndex AS tblIndex ON
-- tblIndex.FY = detail.FY AND
-- tblIndex.Index_No = detail.Index_No
-- INNER JOIN dbo.tblPCA AS tblPCA ON
-- tblPCA.FY = detail.FY AND
-- tblPCA.PCA = detail.PCA
-- INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
-- tblPCAFl.FY = tblPCA.FY AND
-- tblPCAFl.PCA = tblPCA.PCA AND
-- tblPCAFl.Appro_Sym = detail.Appro_Sym AND
-- tblPCAFl.Fund_Src = detail.Fund_Src AND
-- tblPCAFl.Fund_No = detail.Fund_No AND
-- tblPCAFl.Method = detail.Method AND
-- tblPCAFl.Project = detail.Project
-- INNER JOIN dbo.tblAppro AS tblAppro ON
-- tblAppro.FY = tblPCAFl.FY AND
-- tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
-- INNER JOIN dbo.tblAgyDE AS tblAgyDE ON
-- tblAgyDE.Obj_Det = detail.Obj_Det AND
-- tblAgyDE.Agy_Obj = detail.Agy_Obj
-- INNER JOIN dbo.tblObjDe AS tblObjDe ON
-- tblObjDe.Obj_Det = tblAgyDE.Obj_Det
-- INNER JOIN dbo.tblCat AS tblCat ON
-- tblCat.Category = tblObjDe.Category) as myda
SELECT
tblIndex.Dept_Id,
tblIndex.Dpty_Id,
tblIndex.Brch_Id,
tblIndex.Div_Id,
detail.Index_No,
tblIndex.Index_Title,
detail.PCA,
tblPCA.PCA_Title,
PROGLINK = REPLACE(tblPCA.Program+tblPCA.Element+tblPCA.Component+tblPCA.Task, '', '0'),
FUNDLINK = tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
tblAppro.Ref,
detail.Obj_Det,
detail.Agy_Obj,
PYs,
POS = IIF(((detail.Obj_Det = '003') AND (RTRIM(detail.Agy_Obj) = '')), detail.Calc_PYs, 0.0),
Calc_PYs = detail.Calc_PYs,
detail.Calc_Allot,
PCT
FROM
BudgetSummaryDetail AS detail
INNER JOIN dbo.tblIndex AS tblIndex ON
tblIndex.FY = detail.FY AND
tblIndex.Index_No = detail.Index_No
INNER JOIN dbo.tblPCA AS tblPCA ON
tblPCA.FY = detail.FY AND
tblPCA.PCA = detail.PCA
INNER JOIN dbo.tblPCAFl AS tblPCAFl ON
tblPCAFl.FY = tblPCA.FY AND
tblPCAFl.PCA = tblPCA.PCA AND
tblPCAFl.Appro_Sym = detail.Appro_Sym AND
tblPCAFl.Fund_Src = detail.Fund_Src AND
tblPCAFl.Fund_No = detail.Fund_No AND
tblPCAFl.Method = detail.Method AND
tblPCAFl.Project = detail.Project
INNER JOIN dbo.tblAppro AS tblAppro ON
tblAppro.FY = tblPCAFl.FY AND
tblAppro.Appro_Sym = tblPCAFl.Appro_Sym
INNER JOIN dbo.tblAgyDE AS tblAgyDE ON
tblAgyDE.Obj_Det = detail.Obj_Det AND
tblAgyDE.Agy_Obj = detail.Agy_Obj
INNER JOIN dbo.tblObjDe AS tblObjDe ON
tblObjDe.Obj_Det = tblAgyDE.Obj_Det
INNER JOIN dbo.tblCat AS tblCat ON
tblCat.Category = tblObjDe.Category
ORDER BY
tblIndex.Dept_Id,
tblIndex.Dpty_Id,
tblIndex.Brch_Id,
tblIndex.Div_Id,
detail.Index_No,
detail.PCA,
tblPCAFl.Appro_Sym+tblPCAFl.Fund_Src+tblPCAFl.Fund_No+tblPCAFl.Method+ IIF(tblPCAFl.Project = SPACE(6), SPACE(8), tblPCAFl.Project+'00'),
detail.Obj_Det,
detail.Agy_Obj
IF Object_id('tempdb..#Index_No_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #Index_No_ParamValues;
END
IF Object_id('tempdb..#PCA_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #PCA_ParamValues;
END
IF Object_id('tempdb..#Appro_Sym_ParamValues') IS NOT NULL
BEGIN
DROP TABLE #Appro_Sym_ParamValues;
END
RETURN 0
END
GO
We have done a SQL Server upgrade from 2005 to 2014. Post upgrade one of the stored procedures is running very slow. It used to take about 10 mins which has now increased to 23 mins.
On further investigating, the execution time after fresh upgrade was perfectly fine and only after 3-4 executions it gets increased. I tried restoring the fresh database again and can confirm the above behaviour. Can someone help me out, since I have no clue what's happening!
I am a core DBA and not an application DBA so I don't have much knowledge about how stored procedures behave. Any help would be appreciated.
I am running using parameters :
exec [usp_RecalculateMV] '10', 8, 2015
Stored procedure code:
CREATE PROCEDURE [dbo].[usp_RecalculateMV]
(#MarketID nvarchar(100),
#FromMonth int,
#FromYear int)
AS
BEGIN
--variable to hold any errors generated by the procedure
DECLARE #ErrorCode INT
DECLARE #MarketIDs INT
DECLARE #Failed nvarchar(100)
DECLARE #SplitBy nvarchar(10)
DECLARE #StartDate nvarchar(11)
--
-- Changes done by Rupan
-- Start (SER000008289)
DECLARE #cQtytoSplit FLOAT
DECLARE #cOtherQty FLOAT
DECLARE #cSplitThreshold INT
DECLARE #cWeeklySplit NVARCHAR(35)
DECLARE #cWeeklyBufferSplit NVARCHAR(35)
DECLARE #SplitType VARCHAR(15)
DECLARE #cSplitValue FLOAT
DECLARE #jSplit INT
SET #jSplit = 1
DECLARE #iSplit INT
SET #iSplit = 1
DECLARE #cPackCode NVARCHAR(50)
DECLARE #cCustCode NVARCHAR(50)
DECLARE #Week1Cursor INT
DECLARE #Week2Cursor INT
DECLARE #Week3Cursor INT
DECLARE #Week4Cursor INT
DECLARE #QtytoSplitCursor FLOAT
DECLARE #OtherQtyCursor FLOAT
DECLARE #itemp INT
SET #itemp = 1
DECLARE #tempCount INT
DECLARE #tempPackCode NVARCHAR(50)
DECLARE #tempCustomerCode NVARCHAR(50)
DECLARE #tempWeeklyMV VARCHAR(85)
DECLARE #tempWeeklBuffer VARCHAR(85)
DECLARE #tempMVQTY FLOAT
DECLARE #tempBufferQTY FLOAT
CREATE TABLE #tmp_IntialLoad ( ID INT IDENTITY(1,1),
MVQty FLOAT,
BufferQty FLOAT,
SplitThreshold INT,
WeeklyMVQty NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
WeeklyBufferQty NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
PackCode NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
CustomerCode NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS
);
CREATE TABLE #tmp_SplitQTY ( ID INT IDENTITY(1,1),
SplitType VARCHAR(15) COLLATE SQL_Latin1_General_CP1_CI_AS,
QtytoSplit FLOAT,
OtherQty FLOAT,
MarketID NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Code NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
CustomerCode NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Week1 INT,
Week2 INT,
Week3 INT,
Week4 INT,
Week1Buffer INT,
Week2Buffer INT,
Week3Buffer INT,
Week4Buffer INT
);
CREATE TABLE #tmp_SplitBufferQTY ( ID INT IDENTITY(1,1),
SplitType VARCHAR(15) COLLATE SQL_Latin1_General_CP1_CI_AS,
QtytoSplit FLOAT,
OtherQty FLOAT,
MarketID NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Code NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
CustomerCode NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Week1 INT,
Week2 INT,
Week3 INT,
Week4 INT
);
CREATE TABLE #tmp_FinalSplitQTY ( ID INT IDENTITY(1,1),
MarketID NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Code NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
CustomerCode NVARCHAR(85) COLLATE SQL_Latin1_General_CP1_CI_AS,
Week1 INT,
Week2 INT,
Week3 INT,
Week4 INT,
Week1Buffer INT,
Week2Buffer INT,
Week3Buffer INT,
Week4Buffer INT,
QtytoSplit FLOAT,
OtherQty FLOAT
);
-- END
--table struc to hold the split string passed in above
DECLARE #T_TBL_Market TABLE
(
ID INT IDENTITY(1,1),
MarketID int --nvarchar(100)
)
--populate the temporary table with the split market id's
INSERT INTO #T_TBL_Market
SELECT * FROM dbo.Split(#MarketID, ',')
SET #StartDate = dbo.GetSafeDateFormat(1, #FromMonth, #FromYear)
--create a cursor to loop through the market id's
/* Start - Rupan
DECLARE MarketCursor CURSOR FOR
SELECT MarketID FROM #T_TBL_Market
--Open
OPEN MarketCursor
--loop through the markets
FETCH NEXT FROM MarketCursor
INTO #MarketIDs
******* End */
DECLARE #iMarketID INT
SET #iMarketID = 1
DECLARE #iCount INT
SELECT #iCount = COUNT(*) FROM #T_TBL_Market
/* Start - Rupan
WHILE ##FETCH_STATUS = 0
End */
WHILE( #iMarketID <= #iCount )
BEGIN
SELECT #MarketIDs = MarketID FROM #T_TBL_Market WHERE ID = #iMarketID
Print 'Inside While'
--Changes done by Parag on 08-04-2010, inserting values for customer detail
--Deleting old values
DELETE from TBL_CUSTOMER_CODE
INSERT INTO TBL_CUSTOMER_CODE(CustomerSplitID,CustomerID, Week1Split, Week2Split, Week3Split, Week4Split, SplitThreshold, CustomerCode)
SELECT dbo.TBL_CUSTOMER_SPLIT.CustomerSplitID, dbo.TBL_CUSTOMER.CustomerID, ISNULL(dbo.TBL_CUSTOMER_SPLIT.Week1Split, 25) AS Week1Split,
ISNULL(dbo.TBL_CUSTOMER_SPLIT.Week2Split, 25) AS Week2Split, ISNULL(dbo.TBL_CUSTOMER_SPLIT.Week3Split, 25) AS Week3Split,
ISNULL(dbo.TBL_CUSTOMER_SPLIT.Week4Split, 25) AS Week4Split, dbo.TBL_CUSTOMER_SPLIT.SplitThreshold,
ISNULL(dbo.TBL_CUSTOMER.CustomerCdSoldTo, '') + ISNULL(dbo.TBL_CUSTOMER.CustomerCdShipTo, '') AS CustomerCode
FROM dbo.TBL_CUSTOMER LEFT OUTER JOIN
dbo.TBL_CUSTOMER_SPLIT ON dbo.TBL_CUSTOMER.CustomerID = dbo.TBL_CUSTOMER_SPLIT.CustomerID
WHERE TBL_CUSTOMER.marketid =#MarketIDs
--Changes end
--start a transaction to roll back if things go awry
BEGIN TRAN
--delete the data for this market including and after the startdate
Print'Before Delete'
DELETE FROM TBL_CALCULATED_MV
WHERE MarketID = #MarketIDs
AND [Month] >= #StartDate
Print'After Delete'
--check for errors
SELECT #ErrorCode = ##Error
--if no errors continue
IF #ErrorCode = 0
BEGIN
Print'Inserting into CalculatedMV table'
--do the basic recalculation of the MV and Buffer
INSERT INTO TBL_CALCULATED_MV(
MarketName, GroupDescription, MCCode,
ChannelDesc, PackCode, PackDesc, [Month],
MVQty,BufferQty,BufferPercentage,
LocalCustomerCode,LocalCustomerName,
CustomerCdSoldTo, CustomerCdShipTo,
BrandName, BrandCode,
MinMV, MarketID,
IntlCode, EPVOrgCode, AVOrgCode, LDDQty
)
SELECT DISTINCT TBL_MARKET_COMPANY.MarketName, TBL_GROUP.GroupDescription, TBL_MARKET_COMPANY.MCCode,
TBL_CHANNEL.ChannelDesc, VW_BASE_MV.PackCode, TBL_MARKET_PACK.PackDesc, VW_BASE_MV.[Month],
VW_BASE_MV.RoundedBaseMV AS MVQty,
dbo.CalculateBuffer(VW_BASE_MV.RoundedBaseMV, VW_LATEST_BUFFER.MonthValue, VW_LATEST_MINMV.MonthValue) AS BufferQty,
VW_LATEST_BUFFER.MonthValue AS BufferPercentage,
CASE WHEN TBL_CUSTOMER.CustomerCdShipTo IS NULL THEN
TBL_CUSTOMER.CustomerCdSoldTo
ELSE
TBL_CUSTOMER.CustomerCdShipTo
END AS LocalCustomerCode,
TBL_CUSTOMER.CustDescription, TBL_CUSTOMER.CustomerCdSoldTo, TBL_CUSTOMER.CustomerCdShipTo,
TBL_BRAND.BrandName, TBL_BRAND.BrandCode,
VW_LATEST_MINMV.MonthValue, VW_BASE_MV.MarketID,
TBL_MARKET_PACK.IntlCode, TBL_MARKET_COMPANY.EPVOrgCode, TBL_MARKET_COMPANY.AVOrgCode,
VW_BASE_MV.LDD
FROM TBL_CHANNEL
INNER JOIN VW_BASE_MV
ON TBL_CHANNEL.ChannelID = VW_BASE_MV.ChannelID
INNER JOIN TBL_MARKET_COMPANY
ON TBL_MARKET_COMPANY.MarketID = VW_BASE_MV.MarketID
INNER JOIN TBL_GROUP
ON TBL_GROUP.GroupID = TBL_MARKET_COMPANY.GroupID
INNER JOIN TBL_MARKET_PACK
ON VW_BASE_MV.MarketID = TBL_MARKET_PACK.MarketID
AND VW_BASE_MV.PackCode = TBL_MARKET_PACK.PackCode
INNER JOIN TBL_BRAND
ON TBL_BRAND.BrandID = TBL_MARKET_PACK.BrandID
LEFT OUTER JOIN TBL_CUSTOMER
ON VW_BASE_MV.CustomerID = TBL_CUSTOMER.CustomerID
LEFT OUTER JOIN VW_LATEST_BUFFER
ON VW_BASE_MV.MarketID = VW_LATEST_BUFFER.MarketID
AND VW_BASE_MV.PackCode = VW_LATEST_BUFFER.PackCode
AND VW_BASE_MV.ChannelID = VW_LATEST_BUFFER.ChannelID
AND VW_BASE_MV.[Month] = VW_LATEST_BUFFER.[Month]
LEFT OUTER JOIN VW_LATEST_MINMV
ON VW_BASE_MV.MarketID = VW_LATEST_MINMV.MarketID
AND VW_BASE_MV.PackCode = VW_LATEST_MINMV.PackCode
AND VW_BASE_MV.ChannelID = VW_LATEST_MINMV.ChannelID
AND VW_BASE_MV.[Month] = VW_LATEST_MINMV.[Month]
WHERE VW_BASE_MV.[Month] >= #StartDate
AND VW_BASE_MV.MarketID = #MarketIDs
AND VW_BASE_MV.RoundedBaseMV > 0
AND CASE WHEN TBL_CUSTOMER.CustomerCdShipTo IS NULL THEN
TBL_CUSTOMER.CustomerCdSoldTo
ELSE
TBL_CUSTOMER.CustomerCdShipTo
END IS NOT NULL --prevents customer still in the market share table
--but not in the customer table from being passed through
--to the calculated mv table
--check for errors
SELECT #ErrorCode = ##Error
Print 'After Inserting into CalculatedMV table'
END
IF #ErrorCode = 0 -- Start End of Errorcode 1
BEGIN
--find out if this market splits by Pack or by customer
SELECT #SplitBy = ISNULL(SplitBy, 'Unassigned')
FROM TBL_MARKET_COMPANY
WHERE MarketID = #MarketIDs
--calculate the split MV and default the SumWeeklyMV and SumWeeklyBuffer
--fields to the MV and Buffer quantities
IF ISNULL(#SplitBy, 'Unassigned') = 'Unassigned'
BEGIN
UPDATE TBL_CALCULATED_MV
SET
Week1MV = 0,
Week2MV = 0,
Week3MV = 0,
Week4MV = 0,
Week1Buffer = 0,
Week2Buffer = 0,
Week3Buffer = 0,
Week4Buffer = 0,
SumWeeklyMV = MVQty,
SumWeeklyBuffer = BufferQty,
Split = 0
WHERE
TBL_CALCULATED_MV.MarketID = #MarketIDs
AND
TBL_CALCULATED_MV.[Month] >= #StartDate
END
IF #SplitBy = 'Pack' -- Start of Pack
BEGIN
Print 'Entering Pack sum update'
UPDATE TBL_CALCULATED_MV
SET
SumWeeklyMV = MVQty,
SumWeeklyBuffer = BufferQty,
Split = CASE WHEN MP.SplitThreshold IS NULL THEN
0
WHEN MVQty + BufferQty < MP.SplitThreshold THEN
0
ELSE
1
END
FROM TBL_CALCULATED_MV
LEFT OUTER JOIN
VW_PACK_SPLIT
ON
TBL_CALCULATED_MV.PackCode = VW_PACK_SPLIT.PackCode
AND
TBL_CALCULATED_MV.MarketID = VW_PACK_SPLIT.MarketID
INNER JOIN
TBL_MARKET_PACK MP
ON
TBL_CALCULATED_MV.MarketID = MP.MarketID
AND
TBL_CALCULATED_MV.PackCode = MP.PackCode
WHERE
TBL_CALCULATED_MV.MarketID = #MarketIDs
AND
TBL_CALCULATED_MV.[Month] >= #StartDate
Print 'After sum update'
Print'Before inserting into Initialload table'
/* Changes Done By Rupan (SER00008289)*/
INSERT INTO #tmp_IntialLoad
SELECT DISTINCT
MVQty,
BufferQty,
MP.SplitThreshold,
CONVERT(VARCHAR,Week1Split)+','+CONVERT(VARCHAR,Week2Split)+','+CONVERT(VARCHAR,Week3Split)+','+CONVERT(VARCHAR,Week4Split),
CONVERT(VARCHAR,Week1Split)+','+CONVERT(VARCHAR,Week2Split)+','+CONVERT(VARCHAR,Week3Split)+','+CONVERT(VARCHAR,Week4Split),
MP.PackCode,
TBL_CALCULATED_MV.LocalCustomerCode
FROM
TBL_CALCULATED_MV
LEFT OUTER JOIN VW_PACK_SPLIT
ON TBL_CALCULATED_MV.PackCode = VW_PACK_SPLIT.PackCode
AND TBL_CALCULATED_MV.MarketID = VW_PACK_SPLIT.MarketID
INNER JOIN TBL_MARKET_PACK MP
ON TBL_CALCULATED_MV.MarketID = MP.MarketID
AND TBL_CALCULATED_MV.PackCode = MP.PackCode
WHERE TBL_CALCULATED_MV.MarketID = #MarketIDs
AND TBL_CALCULATED_MV.[Month] >= #StartDate
AND TBL_CALCULATED_MV.Split=1
SET #jSplit = 1
Print 'After Initial load and before looping Initial Load'
WHILE(#jSplit <= (SELECT Count(*) FROM #tmp_IntialLoad ))
BEGIN
SELECT #cQtytoSplit = MVQty,
#cOtherQty = BufferQty,
#cSplitThreshold = SplitThreshold,
#cWeeklySplit = WeeklyMVQty,
#cWeeklyBufferSplit = WeeklyBufferQty,
#cPackCode = PackCode,
#cCustCode = CustomerCode
FROM
#tmp_IntialLoad
WHERE
ID = #jSplit
INSERT INTO #tmp_SplitQTY(SplitType,QtytoSplit,OtherQty,MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4)
EXEC CalculateSplitMV_working_SER8289 #cQtytoSplit,#cOtherQty,#cSplitThreshold,#cWeeklySplit,'MV',#MarketIDs,#cPackCode,NULL
INSERT INTO #tmp_SplitBufferQTY(SplitType,QtytoSplit,OtherQty,MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4)
EXEC CalculateSplitMV_working_SER8289 #cOtherQty,#cQtytoSplit,#cSplitThreshold,#cWeeklyBufferSplit,'BUFFER',#MarketIDs,#cPackCode,NULL
SET #jSplit = #jSplit + 1
END
Print 'After looping Initial Load and before updating #tmp_SplitQTY'
UPDATE ts
SET
ts.Week1Buffer = tsb.Week1,
ts.Week2Buffer = tsb.Week2,
ts.Week3Buffer = tsb.Week3,
ts.Week4Buffer = tsb.Week4
FROM
#tmp_SplitQTY ts,#tmp_SplitBufferQTY tsb
WHERE
ts.ID = tsb.ID
AND
ts.MarketID = tsb.MarketID
AND
ts.Code = tsb.Code
SELECT #tempCount = COUNT(*) FROM #tmp_SplitQTY
Print 'After updating #tmp_SplitQTY and before calling usp_Forecast_Calc_BoxSize sp '
WHILE(#itemp <= #tempCount)
BEGIN
SELECT #tempPackCode = Code,
#tempCustomerCode = CustomerCode,
#tempWeeklyMV = CONVERT(VARCHAR,Week1)+','+CONVERT(VARCHAR,Week2)+','+CONVERT(VARCHAR,Week3)+','+CONVERT(VARCHAR,Week4),
#tempWeeklBuffer = CONVERT(VARCHAR,Week1Buffer)+','+CONVERT(VARCHAR,Week2Buffer)+','+CONVERT(VARCHAR,Week3Buffer)+','+CONVERT(VARCHAR,Week4Buffer),
#tempMVQTY = QtytoSplit,
#tempBufferQTY = OtherQty
FROM
#tmp_SplitQTY
WHERE
ID = #itemp
INSERT INTO #tmp_FinalSplitQTY(MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4,Week1Buffer,Week2Buffer,Week3Buffer,Week4Buffer,QtytoSplit,OtherQty)
EXEC usp_Forecast_Calc_BoxSize #tempWeeklyMV,#tempWeeklBuffer,#MarketIDs,#tempPackCode,NULL,#tempMVQTY,#tempBufferQTY
-- EXEC usp_Forecast_Calc_BoxSize '1,0,0,0','1,1,1,0',5,1120200,NULL,1,3
SET #itemp = #itemp + 1
END
PRINT 'after usp_Forecast_Calc_BoxSize and before Entering MV/Buffer Update'
/* Updating MV Quantity Weekly Split value */
UPDATE tc
SET
tc.Week1MV = tfs.Week1,
tc.Week2MV = tfs.Week2,
tc.Week3MV = tfs.Week3,
tc.Week4MV = tfs.Week4,
tc.Week1Buffer = tfs.Week1Buffer,
tc.Week2Buffer = tfs.Week2Buffer,
tc.Week3Buffer = tfs.Week3Buffer,
tc.Week4Buffer = tfs.Week4Buffer
FROM
TBL_CALCULATED_MV tc,#tmp_FinalSplitQTY tfs
WHERE
tc.PackCode = tfs.code
AND
tc.MarketID = tfs.MarketID
AND
tc.MarketID = #MarketIDs
AND
tc.MVQty = tfs.QtytoSplit
AND
tc.BufferQty = tfs.OtherQty
AND
tc.[Month]>= #StartDate
AND
tc.Split=1
PRINT 'after MV/Buffer Update'
END -- End of Pack Condition
IF #SplitBy = 'Customer' -- Start of Customer condition
BEGIN
Print 'Entering Customer Sum update'
UPDATE TBL_CALCULATED_MV
SET
SumWeeklyMV = MVQty,
SumWeeklyBuffer = BufferQty,
Split = CASE WHEN MP.SplitThreshold IS NULL THEN
0
WHEN MVQty + BufferQty < MP.SplitThreshold THEN
0
ELSE
1
END
FROM TBL_CALCULATED_MV
--LEFT OUTER JOIN VW_CUSTOMER_SPLIT
LEFT OUTER JOIN TBL_CUSTOMER_CODE
ON TBL_CALCULATED_MV.LocalCustomerCode = TBL_CUSTOMER_CODE.CustomerCode
--ON TBL_CALCULATED_MV.LocalCustomerCode = VW_CUSTOMER_SPLIT.CustomerCode
INNER JOIN TBL_MARKET_PACK MP
ON TBL_CALCULATED_MV.MarketID = MP.MarketID
AND TBL_CALCULATED_MV.PackCode = MP.PackCode
WHERE TBL_CALCULATED_MV.MarketID = #MarketIDs
AND TBL_CALCULATED_MV.[Month] >= #StartDate
--* Updating MV Quantity Weekly Split value */
/* Updating MV Quantity Weekly Split value */
Print 'After Customer Sum update'
Print'Before inserting into Initialload table'
INSERT INTO #tmp_IntialLoad
SELECT DISTINCT
MVQty,
BufferQty,
MP.SplitThreshold,
CONVERT(VARCHAR,Week1Split)+','+CONVERT(VARCHAR,Week2Split)+','+CONVERT(VARCHAR,Week3Split)+','+CONVERT(VARCHAR,Week4Split),
CONVERT(VARCHAR,Week1Split)+','+CONVERT(VARCHAR,Week2Split)+','+CONVERT(VARCHAR,Week3Split)+','+CONVERT(VARCHAR,Week4Split),
TBL_CALCULATED_MV.PackCode,
TBL_CALCULATED_MV.LocalCustomerCode
FROM
TBL_CALCULATED_MV
--LEFT OUTER JOIN VW_CUSTOMER_SPLIT
LEFT OUTER JOIN TBL_CUSTOMER_CODE
ON TBL_CALCULATED_MV.LocalCustomerCode = TBL_CUSTOMER_CODE.CustomerCode
--ON TBL_CALCULATED_MV.LocalCustomerCode = VW_CUSTOMER_SPLIT.CustomerCode
INNER JOIN TBL_MARKET_PACK MP
ON TBL_CALCULATED_MV.MarketID = MP.MarketID
AND TBL_CALCULATED_MV.PackCode = MP.PackCode
WHERE TBL_CALCULATED_MV.MarketID = #MarketIDs
AND TBL_CALCULATED_MV.[Month] >= #StartDate
AND TBL_CALCULATED_MV.Split=1
SET #jSplit = 1
Print 'After Initial load and before looping Initial Load'
WHILE(#jSplit <= (SELECT Count(*) FROM #tmp_IntialLoad ))
BEGIN
SELECT #cQtytoSplit = MVQty,
#cOtherQty = BufferQty,
#cSplitThreshold = SplitThreshold,
#cWeeklySplit = WeeklyMVQty,
#cWeeklyBufferSplit = WeeklyBufferQty,
#cPackCode = PackCode,
#cCustCode = CustomerCode
FROM
#tmp_IntialLoad
WHERE
ID = #jSplit
INSERT INTO #tmp_SplitQTY(SplitType,QtytoSplit,OtherQty,MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4)
EXEC CalculateSplitMV_working_SER8289 #cQtytoSplit,#cOtherQty,#cSplitThreshold,#cWeeklySplit,'MV',#MarketIDs,#cPackCode,#cCustCode
INSERT INTO #tmp_SplitBufferQTY(SplitType,QtytoSplit,OtherQty,MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4)
EXEC CalculateSplitMV_working_SER8289 #cOtherQty,#cQtytoSplit,#cSplitThreshold,#cWeeklyBufferSplit,'BUFFER',#MarketIDs,#cPackCode,#cCustCode
SET #jSplit = #jSplit + 1
END
Print 'After looping Initial Load and before updating #tmp_SplitQTY'
UPDATE ts
SET
ts.Week1Buffer = tsb.Week1,
ts.Week2Buffer = tsb.Week2,
ts.Week3Buffer = tsb.Week3,
ts.Week4Buffer = tsb.Week4
FROM
#tmp_SplitQTY ts,#tmp_SplitBufferQTY tsb
WHERE
ts.ID = tsb.ID
AND
ts.MarketID = tsb.MarketID
AND
ts.Code = tsb.Code
AND
ts.CustomerCode = tsb.CustomerCode
SELECT #tempCount = COUNT(*) FROM #tmp_SplitQTY
Print 'After updating #tmp_SplitQTY and before calling usp_Forecast_Calc_BoxSize sp '
WHILE(#itemp <= #tempCount)
BEGIN
SELECT #tempPackCode = Code,
#tempCustomerCode = CustomerCode,
#tempWeeklyMV = CONVERT(VARCHAR,Week1)+','+CONVERT(VARCHAR,Week2)+','+CONVERT(VARCHAR,Week3)+','+CONVERT(VARCHAR,Week4),
#tempWeeklBuffer = CONVERT(VARCHAR,Week1Buffer)+','+CONVERT(VARCHAR,Week2Buffer)+','+CONVERT(VARCHAR,Week3Buffer)+','+CONVERT(VARCHAR,Week4Buffer),
#tempMVQTY = QtytoSplit,
#tempBufferQTY = OtherQty
FROM
#tmp_SplitQTY
WHERE
ID = #itemp
INSERT INTO #tmp_FinalSplitQTY(MarketID,Code,CustomerCode,Week1,Week2,Week3,Week4,Week1Buffer,Week2Buffer,Week3Buffer,Week4Buffer,QtytoSplit,OtherQty)
EXEC usp_Forecast_Calc_BoxSize #tempWeeklyMV,#tempWeeklBuffer,#MarketIDs,#tempPackCode,#tempCustomerCode,#tempMVQTY,#tempBufferQTY
SET #itemp = #itemp + 1
END
PRINT 'after usp_Forecast_Calc_BoxSize and before Entering MV/Buffer Update'
/* Updating MV Quantity Weekly Split value */
UPDATE tc
SET
tc.Week1MV = tfs.Week1,
tc.Week2MV = tfs.Week2,
tc.Week3MV = tfs.Week3,
tc.Week4MV = tfs.Week4,
tc.Week1Buffer = tfs.Week1Buffer,
tc.Week2Buffer = tfs.Week2Buffer,
tc.Week3Buffer = tfs.Week3Buffer,
tc.Week4Buffer = tfs.Week4Buffer
FROM
TBL_CALCULATED_MV tc,#tmp_FinalSplitQTY tfs
WHERE
tc.PackCode = tfs.code
AND
tc.MarketID = tfs.MarketID
AND
tc.LocalCustomerCode = tfs.CustomerCode
AND
tc.MarketID = #MarketIDs
AND
tc.MVQty = tfs.QtytoSplit
AND
tc.BufferQty = tfs.OtherQty
AND
tc.[Month]>= #StartDate
AND
tc.Split=1
/* End */
PRINT 'after MV/Buffer Update'
--check for errors
SELECT #ErrorCode = ##Error
END -- End of Customer condition
END -- End of Errorcode 1
IF #ErrorCode = 0
BEGIN
Print 'Inside sumweekly update'
--Update the SumWeeklyMV and SumWeeklyBuffer fields to be the sum of the
--splits for the rows that are to be split
UPDATE TBL_CALCULATED_MV
SET
TBL_CALCULATED_MV.SumWeeklyMV = ISNULL(Week1MV,0) + ISNULL(Week2MV,0) + ISNULL(Week3MV,0) + ISNULL(Week4MV,0),
TBL_CALCULATED_MV.SumWeeklyBuffer = ISNULL(Week1Buffer,0) + ISNULL(Week2Buffer,0) + ISNULL(Week3Buffer,0) + ISNULL(Week4Buffer,0)
WHERE TBL_CALCULATED_MV.Split=1
and TBL_CALCULATED_MV.MarketID = #MarketIDs
AND TBL_CALCULATED_MV.[Month] >= #StartDate
--check for errors
select #ErrorCode = ##Error
END
IF #ErrorCode = 0
COMMIT TRAN
ELSE
BEGIN
ROLLBACK TRAN
set #Failed = #Failed + ',' + #MarketIDs
END
SET #ErrorCode = 0
/* Start - Rupan
FETCH NEXT FROM MarketCursor
INTO #MarketIDs
End */
DELETE FROM #tmp_IntialLoad
DELETE FROM #tmp_SplitQTY
DELETE FROM #tmp_FinalSplitQTY
SET #iMarketID = #iMarketID + 1
END
/*CLOSE MarketCursor
DEALLOCATE MarketCursor
*/
DROP TABLE #tmp_IntialLoad
DROP TABLE #tmp_SplitQTY
DROP TABLE #tmp_FinalSplitQTY
--IF #Failed is null
--SELECT #SuccessFail = 'All markets were successfully re-calculated'
--ELSE
-- SELECT #SuccessFail=#Failed
END -- END of Procedure Begin
GO
If it has not been done yet, you should:
switch to compatibility lever 120
rebuild indexes
update statistics
clear plan cache and force stored procedures recompile
I am getting the following error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
for the query show below:
CREATE PROC [dbo].[Sp_Table1] #ctlg_ipt_event_id int
AS
SET NOCOUNT ON
DECLARE #current_status NCHAR(1), #ready_status_code NCHAR(1)
DECLARE #current_action NCHAR(1), #ready_action_code NCHAR(1), #done_action_code NCHAR(1)
DECLARE #pst_user_id int
SELECT #current_status = status_code
,#current_action = action_code
,#pst_user_id = last_mod_user_id
FROM merch_ctlg_ipt_event
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
Select #ready_status_code = 'o'
, #ready_action_code = 'a'
, #done_action_code = 'b'
IF #current_status <> #ready_status_code OR #current_action <> #ready_action_code
BEGIN
RETURN
END
BEGIN TRAN
declare #rows int
,#err int
,#i int
,#name nvarchar(50) --COLLATE SQL_AltDiction_Pref_CP850_CI_AS
,#resolved_View_Name_category_id int
,#xref_value int
,#availability_start_date datetime
,#availability_end_date datetime
,#status_code int
,#last_mod_user_id int
,#CT datetime
,#supplier_id int
,#View_Name_id int
select #i = 1
,#CT = current_timestamp
Select Distinct mc.name,
mc.resolved_View_Name_category_id,
mc.xref_value,
mc.availability_start_date,
mc.availability_end_date,
mc.status_code,
CASE WHEN mc.last_mod_user_id = 42
THEN #pst_user_id
ELSE mc.last_mod_user_id
END as last_mod_user_id,
CURRENT_tsp
,IDENTITY(int,1,1) as rn
,si.supplier_id
,si.View_Name_id
into #temp
FROM View_Name AS si
JOIN merch_ctlg_ipt_View_Name AS mc
ON mc.supplier_id = si.supplier_id
AND mc.resolved_View_Name_id = si.View_Name_id
AND mc.cat_imp_event_id = #ctlg_ipt_event_id
AND mc.accept_flag = 'y'
WHERE si.shipper_flag = 'n'
select #rows=##ROWCOUNT,#err=##error
if #rows > 0 and #err=0
Begin
While #i <=#rows
begin
SElect #name = name,
#resolved_View_Name_category_id = resolved_View_Name_category_id,
#xref_value = xref_value,
#availability_start_date = availability_start_date,
#availability_end_date = availability_end_date,
#status_code = mc.status_code,
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
,#supplier_id=supplier_id
,#View_Name_id=View_Name_id
from #temp
Where rn=#i
UPDATE View_Name
SET name = #name,
View_Name_category_id = #resolved_View_Name_category_id,
xref_value = #xref_value,
availability_start_date = #availability_start_date,
availability_end_date = #availability_end_date,
status_code = #status_code,
last_mod_user_id = #last_mod_user_id ,
last_mod_timestamp = #CT
Where #sup_id = supplier_id
AND #View_Name_id = View_Name_id
AND shipper_flag = 'n'
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
End
End
UPDATE
merch_ctlg_ipt_event
SET action_code = #done_action_code,
last_mod_timestamp = #CT
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
Return
go
Could you please help ?
You have 2 commas in a row here
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
Also probably not relevant to the error message but you have a line
Where #sup_id = supplier_id
but the declared variable is #supplier_id