Reset column value everyday - sql

My column needs to start from 1000 everyday. For every new entry, this number increments by 1. The next day, it should revert to 1000 again. How can I make this happen?

CREATE TABLE [dbo].[GN_GnNm_Generate_Number_T](
[GnNm_Code] [varchar](50) NOT NULL,
[GnNm_Pad_With] [varchar](3) NOT NULL,
[GnNm_No_Of_Times] [varchar](6) NOT NULL,
[GnNm_Increment_No] [int] NOT NULL, /* Starting No eg:1 or 1000 */
[GnNm_Recycle] [char](1) NOT NULL, /* Recycle Type D-Daywise Y-yearwise M-Monthwise*/
[GnNm_Recycle_Type] [varchar](1) NOT NULL,
[GnNm_Recycle_Date] [datetime] NULL
) ON [PRIMARY]
GO
INSERT INTO GN_GnNm_Generate_Number_T
VALUES ('V', '0','5','1000','D','Y',GETDATE())
/* Run & Execute this store procedure for increment no. */
/* Automatically recycle everyday. */
CREATE PROCEDURE [dbo].[usp_Genrate_Number]
#Code_Text Varchar(50), #Gen_Pad varchar(3), #Recycle Varchar(1), #Gen_Code Varchar(10)='' OUTPUT
AS
DECLARE #Pad_With Char(1), #Increment_No int, #No_Of_Times Varchar(6), #Gen_No Varchar(4),
#Recycle_Type Varchar(1), #Recycle_Date Datetime, #EndofMonth Datetime, #EndofYear Datetime
BEGIN
SELECT #Pad_With = GnNm_Pad_With , #No_Of_Times = GnNm_No_Of_Times,
#Recycle_Type = GnNm_Recycle_Type, #Recycle_Date = GnNm_Recycle_Date
FROM GN_GnNm_Generate_Number_T
WHERE GnNm_Code = #Code_Text
SELECT #EndofMonth = DATEADD(MONTH,1+DATEDIFF(MONTH,0,#Recycle_Date),-1);
SELECT #EndofYear = DATEADD(YEAR,1,#Recycle_Date)
IF #Recycle = 'Y'
BEGIN
IF #Recycle_Type = 'D' AND #Recycle_Date < CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME)
BEGIN
UPDATE GN_GnNm_Generate_Number_T
SET GnNm_Increment_No = 1000,
GnNm_Recycle_Date = CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME)
WHERE GnNm_Code = #Code_Text
END
IF #Recycle_Type = 'M' AND CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME) > #EndofMonth
BEGIN
UPDATE GN_GnNm_Generate_Number_T
SET GnNm_Increment_No = 0,
GnNm_Recycle_Date = CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME)
WHERE GnNm_Code = #Code_Text
END
IF #Recycle_Type = 'Y' AND CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME) = #EndofYear
BEGIN
UPDATE GN_GnNm_Generate_Number_T
SET GnNm_Increment_No = 0,
GnNm_Recycle_Date = CAST(CONVERT(VARCHAR,GETDATE(),102)AS DATETIME)
WHERE GnNm_Code = #Code_Text
END
END
SELECT #Increment_No = GnNm_Increment_No
FROM GN_GnNm_Generate_Number_T
WHERE GnNm_Code = #Code_Text
SET #Increment_No = #Increment_No + 1
SELECT #Gen_Code = #Gen_Pad + REPLICATE(''+#Pad_With+'',#No_Of_Times - (LEN(#Increment_No)))+CONVERT(VARCHAR,#Increment_No)
UPDATE GN_GnNm_Generate_Number_T
SET GnNm_Increment_No = #Increment_No
WHERE GnNm_Code = #Code_Text
SELECT #Gen_Code
RETURN
END

Suppose table name is 'Table_1'
Auto incremental column name is 'ID'
Date column name is 'EntryDate' (Assume Table_1 have this column)
DECLARE #NewId int = 0
IF EXISTS (select * from Table_1 where EntryDate=GETDATE() and ID=1000)
#NewId = (select max(ID) from Table_1) + 1
ELSE
#NewId = 1000
INSERT INTO TABLE_1(ID,EntryDate) VALUES (#NewId,GETDATE())

Related

BizTalk 2013R2 SQL Query Timeouts

Using BizTalk to call a SQL Server stored procedure (see below), which:
Writes data to 5 tables
Checks each table to see if the record exists
Updates or Inserts accordingly
The problem is that when BizTalk receives hundreds of calls, the stored procedure is called each time which appears to add an overhead to the SQL Server and eventually causes timeout errors returned in BizTalk, resulting in the data not being written to the database.
Can anyone advise on the best way to optimise my query so that it processes these tables without much overhead, or have I got it optimised enough already?
USE [MDH]
GO
/****** Object: StoredProcedure [dbo].[spcuPersonStudentProgrammeModule] Script Date: 8/15/2022 2:29:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spcuPersonStudentProgrammeModule]
-- person/personref params
#student_id VARCHAR(max)
,#account_id VARCHAR(max) = NULL
,#prefix_honorific VARCHAR(max) = NULL
,#first_name VARCHAR(max) = NULL
,#middle_name VARCHAR(max) = NULL
,#surname VARCHAR(max) = NULL
,#familiar_name VARCHAR(max) = NULL
,#date_of_birth DATE = NULL
,#external_email_address VARCHAR(max) = NULL
,#mobile_phone_no VARCHAR(max) = NULL
,#gender VARCHAR(max) = NULL
,#ethnicity VARCHAR(max) = NULL
,#domicile VARCHAR(max) = NULL
,#disability VARCHAR(max) = NULL
,#nationality VARCHAR(max) = NULL
,#telephone_no VARCHAR(max) = NULL
,#prev_surname VARCHAR(max) = NULL
,#country_of_birth VARCHAR(max) = NULL
-- student params
,#student_email_address VARCHAR(max) = NULL
,#currently_studying_flag VARCHAR(max) = NULL
,#HesaStudentID VARCHAR(max) = NULL
,#UCAS_ID VARCHAR(max) = NULL
,#uln VARCHAR(max) = NULL
,#VisaReq VARCHAR(max) = NULL
,#PurposeOfResidency VARCHAR(max) = NULL
,#cas_status VARCHAR(max) = NULL
,#student_status VARCHAR(max) = NULL
,#source_system VARCHAR(max) = NULL
,#main_programme_code VARCHAR(max) = NULL
,#type VARCHAR(max) = NULL
,#student_support_no VARCHAR(max) = NULL
,#exam_id VARCHAR(max) = NULL
,#su_opt VARCHAR(max) = NULL
,#change_type VARCHAR(max) = NULL
,#international_sponsored_students varchar(80) = null
,#visa_type VARCHAR(max) = null
-- student_programmes params
,#programme_code VARCHAR(50)
,#programme_description VARCHAR(MAX) = NULL
,#start_date DATETIME = NULL
,#end_date DATETIME = NULL
,#mdh_stage_code VARCHAR(MAX) = NULL
,#main_award_flag VARCHAR(10) = NULL
,#load_category VARCHAR(10) = NULL
,#qualification_level VARCHAR(10) = NULL
,#student_study_level VARCHAR(10) = NULL
,#school_code VARCHAR(10) = NULL
,#college_code VARCHAR(10) = NULL
,#campus_code VARCHAR(10) = NULL
,#graduate_yn VARCHAR(10) = NULL
,#is_wbdl VARCHAR(80) = NULL
,#ul_qual_aim VARCHAR(MAX) = NULL
,#ul_qual_aim_desc VARCHAR(MAX) = NULL
-- student_modules params
,#module_code VARCHAR(50)
,#module_desc VARCHAR(MAX) = NULL
,#mod_date_time DATETIME = NULL
-- student_address params
,#perm_address1 VARCHAR(50) = NULL
,#perm_address2 VARCHAR(50) = NULL
,#perm_address3 VARCHAR(50) = NULL
,#perm_address4 VARCHAR(50) = NULL
,#perm_address5 VARCHAR(50) = NULL
,#perm_postcode VARCHAR(50) = NULL
,#perm_country_code VARCHAR(50) = NULL
,#term_address1 VARCHAR(50) = NULL
,#term_address2 VARCHAR(50) = NULL
,#term_address3 VARCHAR(50) = NULL
,#term_address4 VARCHAR(50) = NULL
,#term_address5 VARCHAR(50) = NULL
,#term_postcode VARCHAR(50) = NULL
,#term_country_code VARCHAR(50) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #person_id UNIQUEIDENTIFIER
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
-- Create/Update person_test/person_reference_test
IF EXISTS ( SELECT person_id FROM dbo.person_reference WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
BEGIN
SELECT 'Student exists, updating'
SET #person_id = ( SELECT person_id FROM dbo.person_reference WITH (NOLOCK) WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
UPDATE person
SET prefix_honorific = CASE WHEN #prefix_honorific = 'null' or #prefix_honorific is null or #prefix_honorific = '' THEN prefix_honorific ELSE #prefix_honorific END
,first_name = ISNULL(#first_name, first_name)
,middle_name = ISNULL(#middle_name, middle_name)
,surname = ISNULL(#surname, surname)
,familiar_name = #familiar_name
,date_of_birth = ISNULL(#date_of_birth, date_of_birth)
,external_email_address = ISNULL(#external_email_address, external_email_address)
,gender = ISNULL(#gender, gender)
,ethnicity = ISNULL(#ethnicity, ethnicity)
,domicile = ISNULL(#domicile, domicile)
,disability = ISNULL(#telephone_no, disability)
,telephone_no = ISNULL(#telephone_no, telephone_no)
,prev_surname = ISNULL(#prev_surname, prev_surname)
,country_of_birth = ISNULL(#country_of_birth, country_of_birth)
,proc_date_time = GETDATE()
,mobile_phone_no = ISNULL(#mobile_phone_no, mobile_phone_no)
,nationality = ISNULL(#nationality, nationality)
WHERE person_id_guid = #person_id
IF #account_id IS NOT NULL
BEGIN
UPDATE dbo.person_reference
SET account_id = #account_id
,proc_date_time = GETDATE()
WHERE person_id = #person_id
END
END
ELSE
BEGIN
SELECT 'Student does not exist, creating'
--INSERT person
SET #person_id = NEWID()
INSERT INTO dbo.person (
person_id_guid
,prefix_honorific
,first_name
,middle_name
,surname
,familiar_name
,date_of_birth
,external_email_address
,mobile_phone_no
,gender
,ethnicity
,domicile
,disability
,nationality
,telephone_no
,prev_surname
,country_of_birth
,source_system
,proc_date_time
)
VALUES (
#person_id
,#prefix_honorific
,#first_name
,#middle_name
,#surname
,#familiar_name
,#date_of_birth
,#external_email_address
,#mobile_phone_no
,#gender
,#ethnicity
,#domicile
,#disability
,#nationality
,#telephone_no
,#prev_surname
,'OneUni'
,#country_of_birth
,GETDATE()
)
--INSERT person_reference
INSERT INTO dbo.person_reference (
person_id
,student_id
,proc_date_time
,account_id
)
VALUES (
#person_id
,#student_id
,GETDATE()
,#account_id
)
END
-- Create/Update student
IF EXISTS ( SELECT account_id FROM dbo.student WITH (NOLOCK) WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
BEGIN
SELECT 'Student exists, updating'
UPDATE student
SET
--account_id = #account_id
--,student_id = #student_id
ucas_id = #UCAS_ID
,unique_learner_number = #uln
,main_programme_code = isnull(#main_programme_code, main_programme_code)
,student_email_address = #student_email_address
,currently_studying_flag = #currently_studying_flag
,hesa_student_id = #HesaStudentID
,visa_required = #VisaReq
,cas_status = #cas_status
,student_status = #student_status
,purpose_of_residency = #PurposeOfResidency
,mod_date_time = GETDATE()
,student_support_no = #student_support_no
,source_system = #source_system
,exam_id = #exam_id
,su_opt = #su_opt
,international_sponsored_students = #international_sponsored_students
,visa_type = #visa_type
WHERE account_id = #account_id
END
-- Create Student/Student Programme/Student Module
ELSE
BEGIN
SELECT 'Student does not exist, creating'
SET #person_id = ( SELECT person_id FROM dbo.person_reference WITH (NOLOCK) WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
INSERT INTO student (
person_id_guid
,account_id
,ucas_id
,unique_learner_number
,student_email_address
,currently_studying_flag
,hesa_student_id
,visa_required
,cas_status
,student_status
,purpose_of_residency
,proc_date_time
,source_system
,main_programme_code
,student_id
,student_support_no
,exam_id
,su_opt
,international_sponsored_students
,visa_type
)
VALUES (
#person_id
,#account_id
,#UCAS_ID
,#uln
,#student_email_address
,#currently_studying_flag
,#HesaStudentID
,#VisaReq
,#cas_status
,#student_status
,#PurposeOfResidency
,getdate()
,#source_system
,#main_programme_code
,#student_id
,#student_support_no
,#exam_id
,#su_opt
,#international_sponsored_students
,#visa_type
)
END
-- Create/Update student_programmes if change_record is 'Course'
IF #change_type = 'Programme'
BEGIN
-- Create/Update student_programmes
IF EXISTS ( SELECT student_id FROM student_programmes WITH (NOLOCK) WHERE account_id = #account_id and programme_code = #programme_code)
BEGIN
SELECT 'Student Programme exists, updating'
--UPDATE student_programme? (Wait for confirmation)
UPDATE student_programmes
SET
--account_id = #account_id
--,student_id = #student_id
--course_code = #course_code
programme_description = #programme_description
,[start_date] = #start_date
,end_date = #end_date
,mdh_stage_code = #mdh_stage_code
,main_award_flag = #main_award_flag
,load_category = #load_category
,qualification_level = #qualification_level
,student_study_level = #student_study_level
,is_wbdl = #is_wbdl
,school_code = #school_code
,college_code = #college_code
,campus_code = #campus_code
,ul_qual_aim = #ul_qual_aim
,ul_qual_aim_description = #ul_qual_aim_desc
,mod_date_time = GETDATE()
WHERE account_id = #account_id
and programme_code = #programme_code
END
ELSE
BEGIN
SELECT 'Student Programme does not exist, creating'
SET #person_id = ( SELECT person_id FROM dbo.person_reference WITH (NOLOCK) WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
--INSERT student_programme
INSERT INTO student_programmes (
person_id_guid
,account_id
,student_id
,programme_code
,programme_description
,[start_date]
,end_date
,mdh_stage_code
,main_award_flag
,load_category
,qualification_level
,student_study_level
,is_wbdl
,school_code
,college_code
,campus_code
,ul_qual_aim
,ul_qual_aim_description
,mod_date_time
)
VALUES (
#person_id
,#account_id
,#student_id
,#programme_code
,#programme_description
,#start_date
,#end_date
,#mdh_stage_code
,#main_award_flag
,#load_category
,#qualification_level
,#student_study_level
,#is_wbdl
,#school_code
,#college_code
,#campus_code
,#ul_qual_aim
,#ul_qual_aim_desc
,GETDATE()
)
END
END
-- Create/Update student_modules if change_record is 'Module'
IF #change_type = 'Module'
BEGIN
IF EXISTS ( SELECT student_id FROM student_modules WITH (NOLOCK) WHERE account_id = #account_id and programme_code = #programme_code and module_code = #module_code)
BEGIN
SELECT 'Student Module exists, updating'
--UPDATE student_module? (Wait for confirmation)
UPDATE student_modules
SET
--account_id = #account_id
--,student_id = #student_id
--course_code = #course_code
--module_code = #module_code
module_description = #module_desc
,mdh_stage_code = #mdh_stage_code
,student_study_level = #student_study_level
,mod_date_time = GETDATE()
WHERE account_id = #account_id
and programme_code = #programme_code
and module_code = #module_code
END
ELSE
BEGIN
SELECT 'Student Module does not exist, creating'
SET #person_id = ( SELECT person_id FROM dbo.person_reference WITH (NOLOCK) WHERE account_id = #account_id and ISNULL(status,'') <> 'Delete')
-- If the programme for the module/student doesnt exist, insert it
IF NOT EXISTS ( SELECT student_id FROM dbo.student_programmes WITH (NOLOCK) WHERE account_id = #account_id and programme_code = #programme_code)
BEGIN
SET #person_id = ( SELECT person_id FROM dbo.person_reference WITH (NOLOCK) WHERE account_id = #account_id )
--INSERT student_programme
INSERT INTO student_programmes (
person_id_guid
,account_id
,student_id
,programme_code
,programme_description
,[start_date]
,end_date
,mdh_stage_code
,main_award_flag
,load_category
,qualification_level
,student_study_level
,is_wbdl
,school_code
,college_code
,campus_code
,ul_qual_aim
,ul_qual_aim_description
,mod_date_time
)
VALUES (
#person_id
,#account_id
,#student_id
,#programme_code
,#programme_description
,#start_date
,#end_date
,#mdh_stage_code
,#main_award_flag
,#load_category
,#qualification_level
,#student_study_level
,#is_wbdl
,#school_code
,#college_code
,#campus_code
,#ul_qual_aim
,#ul_qual_aim_desc
,GETDATE()
)
END
--INSERT student_module
INSERT INTO student_modules (
person_id_guid
,account_id
,student_id
,programme_code
,module_code
,module_description
,mdh_stage_code
,student_study_level
,mod_date_time
)
VALUES (
#person_id
,#account_id
,#student_id
,#programme_code
,#module_code
,#module_desc
,#mdh_stage_code
,#student_study_level
,GETDATE()
)
END
END
END

Error converting data type varchar to numeric in sql server

I have created a stored procedure for Save InvoicePayment. When I tried to execute the stored procedure, I get the below error:
Msg 8114, Level 16, State 5, Procedure USP_SaveInvoicePayment_LKO,
Line 0 [Batch Start Line 118] Error converting data type varchar to
numeric.
ALTER PROC Usp_saveinvoicepayment_lko #RECEIPTNO VARCHAR(500),
#INVOICEID BIGINT,
#PayableAmount NUMERIC(10, 2),
#RECEIPTDT DATE,
#PAYMENTMODE VARCHAR(50),
#TRANREF VARCHAR(500),
#USERID BIGINT,
#CHEQUEDATE DATE,
#isValid INT,
#remark VARCHAR(100),
#InvoiceNo VARCHAR(50),
#PaymentRecieved VARCHAR(20),
#PreviousBalance NUMERIC(10, 2),
#ChequeNumber VARCHAR(20),
#PaymentMonth VARCHAR(20),
#PaymentDate DATE,
#CollectorMobile INT,
#Latitude NUMERIC(10, 2),
#Longitude NUMERIC(10, 2),
#RESPONSECODE INT output,
#RESPONSEMESSAGE VARCHAR(255) output,
#IDRESPONSE VARCHAR(200) output
AS
SET nocount ON
BEGIN
--declare #PRJCD varchar(10),
--#KML GEOMETRY ,
--#rowcount int
BEGIN try
--SELECT #PRJCD=PRJCD FROM PRJMST WHERE ID=#PRJID
IF #RECEIPTNO IS NULL
BEGIN
DECLARE #id_out TABLE
(
id VARCHAR(200)
)
--set #ENTRYDATE=getdate()
-- select
convert(varchar,isnull(max(convert(numeric,substring(receiptno,21,50)))+1,1))
from invoicepayment where invoiceid=#invoiceid
INSERT INTO invoicepayment_lko
(receiptno,
invoiceid,
payableamount,
receiptdt,
paymentmode,
trnreference,
userid,
entrydate,
chequedate,
isvalid,
remark,
invoiceno,
paymentrecieved,
previousbalance,
chequenumber,
paymentmonth,
paymentdate,
collectormobile,
latitude,
longitude)
output inserted.receiptno
INTO #id_out
VALUES ( #INVOICENO + '/REC/'
+ (SELECT CONVERT(VARCHAR, Isnull(
Max(CONVERT(NUMERIC, Substring(
receiptno, 21,
50
)))
+ 1, 1))
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid),
#INVOICEID,
#PayableAmount,
#RECEIPTDT,
#PAYMENTMODE,
#TRANREF,
#USERID,
Getdate(),
#CHEQUEDATE,
#isValid,
#remark,
#InvoiceNo,
#PaymentRecieved,
#PreviousBalance,
#ChequeNumber,
#PaymentMonth,
#PaymentDate,
#CollectorMobile,
#Latitude,
#Longitude)
SELECT #IDRESPONSE = id
FROM #id_out
SELECT Ident_current(id)
FROM invoicepayment_lko
UPDATE invoicedetails
SET balanceamt = balanceamt - #PayableAmount
WHERE id = #INVOICEID
END
ELSE
BEGIN
UPDATE invoicepayment_lko
SET chequedate = #CHEQUEDATE,
invoiceid = #INVOICEID,
payableamount = #PayableAmount,
receiptdt = #RECEIPTDT,
paymentmode = #PAYMENTMODE,
trnreference = #TRANREF,
userid = #USERID,
updatedt = Getdate(),
isvalid = #isValid,
remark = #remark,
invoiceno = #InvoiceNo,
paymentrecieved = #PaymentRecieved,
previousbalance = #PreviousBalance,
chequenumber = #ChequeNumber,
paymentmonth = #PaymentMonth,
paymentdate = #PaymentDate,
collectormobile = #CollectorMobile,
latitude = #Latitude,
longitude = #Longitude
WHERE receiptno = #RECEIPTNO
SET #IDRESPONSE = #RECEIPTNO
END
DECLARE #totalPayment NUMERIC(10, 2)
SELECT #totalPayment = Sum(payableamount)
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid
AND isvalid = 1
SELECT #totalPayment,
#invoiceid
END try
BEGIN catch
SELECT #RESPONSECODE = Error_number(),
#RESPONSEMESSAGE = Error_message();
--set #RESPONSEMESSAGE= #prjid;
SELECT #RESPONSECODE,
#RESPONSEMESSAGE
END catch
IF #RESPONSECODE IS NULL
BEGIN
IF #isValid = 0
BEGIN
SET #RESPONSEMESSAGE = 'Payment marked as Invalid'
END
ELSE
BEGIN
SET #RESPONSEMESSAGE = 'Payment created/Updated
Successfully'
END
SET #RESPONSECODE = 200
END
END
--Execution
DECLARE #RESPONSECODE INT = 20,
#RESPONSEMESSAGE VARCHAR(255) = 'Payment Created',
#IDRESPONSE VARCHAR(200) = 'No Response'
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739,
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
Please check your input again. As per the parameters passed in procedure
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739, --- this is one of the reason for your error as you took this as int, but this value will definitly not convert into int.
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
If you can see for phone number is taken as int and int is not right data type for your field mobile number, either take BigInt or use varchar
My suggestion for mobile number field.
#CollectorMobile BIGINT or VARCHAR(15)

Sql Scope_Identity() return Null?

I am facing this issue that my stored proc always return NULL though i have set my #output variable as well.I want to get last inserted scope Id from the table.
can someone help me where i have got wrong?
ALTER PROC spAddOrUpdateMember
#pMemberId INT = 0 ,
#pFirstName VARCHAR(50) = 'aa',
#pLastName VARCHAR(50)='aa' ,
#pMemberCode VARCHAR(15) = '12312',
#pDOB DATE = '03/10/2019',
#pGrade INT = 2 ,
#pCNIC VARCHAR(14) = '3423434',
#pFatherName VARCHAR(50) = 'asdasd' ,
#pCurrentAddress VARCHAR(MAX) = 'asds' ,
#pPermanentAddress VARCHAR(MAX) = 'fgdf',
#pEmploymentAddress VARCHAR(MAX) = 'ytuyu' ,
#pNationality INT =2
#output int = 0 output
AS
BEGIN
IF #pMemberId > 0
BEGIN
---UPDATE ME
UPDATE [dbo].[QC_Member_Profile]
SET
[FirstName] = #pFirstName
,[LastName] = #pLastName
,[DOB] = #pDOB
,[CNIC] = #pCNIC
,[FatherName] = #pFatherName
,[CurrentAddress] = #pCurrentAddress
,[PermanentAddress] = #pPermanentAddress
,[Nationality] = #pNationality
,[MemberTypeId] =#pMemberTypeId
WHERE MemberId = #pMemberId
END
ELSE
BEGIN
---INSERT ME
INSERT INTO QC_Member_Profile VALUES(
dbo.PIdentityKey(0),
#pFirstName,
#pLastName,
#pDOB,
#pCNIC,
#pFatherName,
#pCurrentAddress,
#pPermanentAddress,
#pNationality,
)
set #output = SCOPE_IDENTITY();
SELECT #output = SCOPE_IDENTITY();
select #output
END
END
I've guessed the name of your ID column, however, this should work. You'll need to amend the name of your ID column if it isn't called MemberID or if it doesn't have the data type int:
ALTER PROC spAddOrUpdateMember #pMemberId int = 0,
#pFirstName varchar(50) = 'aa',
#pLastName varchar(50) = 'aa',
#pMemberCode varchar(15) = '12312',
#pDOB date = '03/10/2019',
#pGrade int = 2,
#pCNIC varchar(14) = '3423434',
#pFatherName varchar(50) = 'asdasd',
#pCurrentAddress varchar(MAX) = 'asds',
#pPermanentAddress varchar(MAX) = 'fgdf',
#pEmploymentAddress varchar(MAX) = 'ytuyu',
#pNationality int = 2,
#output int = 0 OUTPUT
AS
BEGIN
IF #pMemberId > 0
BEGIN
UPDATE [dbo].[QC_Member_Profile]
SET [FirstName] = #pFirstName,
[LastName] = #pLastName,
[DOB] = #pDOB,
[CNIC] = #pCNIC,
[FatherName] = #pFatherName,
[CurrentAddress] = #pCurrentAddress,
[PermanentAddress] = #pPermanentAddress,
[Nationality] = #pNationality,
[MemberTypeId] = #pMemberTypeId
WHERE MemberId = #pMemberId;
END;
ELSE
BEGIN
DECLARE #ins table (OutputID int);
INSERT INTO QC_Member_Profile
OUTPUT Inserted.MemberID --guessed name
INTO #Ins
VALUES (dbo.PIdentityKey(0), #pFirstName, #pLastName, #pDOB, #pCNIC, #pFatherName, #pCurrentAddress, #pPermanentAddress, #pNationality);
SELECT #output = OutputID
FROM #ins;
SELECT #Output;
END;
END;
I've also fixed the syntax errors that were in your original question.

Stored Procedure slowness after upgrade to SQL Server 2014

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

How to run stored procedure query between 2 table & insert data base on reference column?

I've created a simple stored procedure to update my Sample_TAG_NUMBERTEST table but I need it to get an ItemCode from another table PartItem by using both SOLine & SONbr to do the query but I don't know how to write it.
2nd thing I need to do is when my StatusCode column is N001 then my DESC column will automatically insert NEW ORDER data value, for PR002 my DESC column will become Progress.
How can I do that? Thanks in advance.
ALTER PROCEDURE [dbo].[SampleTagNumberUpdate]
#sONbr nvarchar(50) = NULL,
#SOLine nvarchar(50) = NULL,
#SerialNbr nvarchar(50) = NULL,
#StatusCode nvarchar(50) = NULL,
#PackType nvarchar(50) = NULL,
#PalletID nvarchar(50) = NULL,
#PackingListNo nvarchar(50) = NULL,
#ItemCode nvarchar(50) = NULL,
#CrDateTime nvarchar(50) = NULL,
#CrUserID nvarchar(50) = NULL,
#return nvarchar(50) = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT sONbr , SOLine
FROM [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
WHERE sONbr = #sONbr AND SOLine = #SOLine)
BEGIN
UPDATE [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
SET SerialNbr = #SerialNbr
,StatusCode = #StatusCode
,PackType = #PackType
,PalletID = #PalletID
,PackingListNo = #PackingListNo
,ItemCode = #ItemCode
,LastUpdDateTime = GETDATE()
,LastUpdUserID = #CrUserID
WHERE sONbr = #sONbr AND SOLine = #SOLine
IF ##ERROR <> 0
Set #Return = 'UPDATE FAILED'
ELSE
Set #Return = 'UPDATE SUCCESSFULLY'
END
ELSE
BEGIN
INSERT INTO [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST](SONbr, SOLine, SerialNbr
,StatusCode
,PackType
,PalletID
,PackingListNo
,ItemCode
,CrDateTime
,CrUserID)
VALUES(#sONbr, #SOLine, #SerialNbr, #StatusCode, #PackType
,#PalletID
,#PackingListNo
,#ItemCode
,GETDATE()
,#CrUserID)
IF ##ERROR <> 0
Set #Return = 'INSERT DATA FAILED'
ELSE
Set #Return = 'INSERT DATA SUCCESSFULLY'
END
END
I believe I have provided an example for both questions below:
UPDATE T
SET ItemCode = (SELECT PI.ItemCode FROM PartItem AS PI WHERE PI.SO = #SO AND PI.SO_LINE = #SO_LINE),
DESC = CASE #StatusCode WHEN 'N001' THEN 'NEW ORDER'
ELSE CASE #StatusCode WHEN 'PR002' THEN 'PROGRESS' ELSE '' END
END,
<other columns here...>
FROM SAMPLE_TAG_NUMBERTEST AS T