Adding a SPACE in my Sql server query change the result set - sql

I have a SQL server query with me.. When i add a Space anywhere in the Query it changes the result set to 410 rows to 38 rows.
How could this be possible?
Thanks in Advance..
Declare #ReportDate date, #Range varchar(50), #Missing bit = 1
--declare #ReportDate datetime, #Range varchar(50) = '', #Missing bit = 0
--declare #ReportDate date, #Range varchar(50)
declare #RangeId int
set #ReportDate = '30 Apr 2014'
set #Range = ''
select #RangeId = ID from fs.FundGroup where Name = #Range
declare #FundProperty table (FundId int, FundCode varchar(25), FundName varchar(255), FundRange varchar(50), ParentFundCode varchar(25), ParentFundId int, AllocationType varchar(25), SourceName varchar(255), UpdatedSourceName varchar(255), AllocationTypeId int)
if #Range = ''
insert into #FundProperty(FundId, FundCode, FundName, FundRange, AllocationType, SourceName)
select F.FundId, F.FundCode, F.FundName, FG.Name, PT.Name, S.Name
from fs.FundDataSource FDS, fs.Fund F, fs.PropertyType PT, fs.Source S, fs.FundGroup FG
where FDS.FundId = F.FundId
and FDS.PropertyTypeId = PT.Id
and FDS.SourceId = S.Id
and F.FundGroupId = FG.Id
and S.Name like '%PPMA%'
and PT.Name not like '%top10%'
else
insert into #FundProperty(FundId, FundCode, FundName, FundRange, AllocationType, SourceName)
select F.FundId, F.FundCode, F.FundName, FG.Name, PT.Name, S.Name
from fs.FundDataSource FDS, fs.Fund F, fs.PropertyType PT, fs.Source S, fs.FundGroup FG
where FDS.FundId = F.FundId
and FDS.PropertyTypeId = PT.Id
and FDS.SourceId = S.Id
and F.FundGroupId = FG.Id
and S.Name like '%PPMA%'
and PT.Name not like '%top10%'
and F.FundGroupId = #RangeId
update #FundProperty set UpdatedSourceName = SourceName
update #FundProperty set ParentFundId = F1.FundId, ParentFundCode = F1.FundCode
from fs.Fund F1, fs.FundIdentifier FI, #FundProperty FP, fs.Fund F2
where FI.FundId = FP.FundId
and F1.FundCode = FI.[Parent Fund Code]
and F2.FundId = FI.FundId
and F1.FundGroupId = F2.FundGroupId
update #FundProperty set AllocationTypeId = Id from fs.AllocationType AT, #FundProperty FP
where AT.Name = case when FP.AllocationType = 'Rating' then 'Credit Rating' else FP.AllocationType end
--select * from #FundProperty
create table #Allocations(FundCode varchar(25), FundName varchar(255), FundRange varchar(50), AllocationType varchar(50), UpdatedSourceName varchar(255), PositionsName varchar(255), ISIN varchar(50), Percentage float, PPMAName varchar(255), AssetName varchar(255), Maturity varchar(50), SnPRating varchar(25), MoodyRating varchar(25))
insert into #Allocations(FundCode,FundName,FundRange,AllocationType,UpdatedSourceName,PositionsName,ISIN,Percentage)
select distinct FP.ParentFundCode, FP.FundName, FP.FundRange, FP.AllocationType, FP.UpdatedSourceName, ALS.Name, ALS.ISIN, ALC.Percentage
from fs.Allocation ALC, fs.AllocationSecurity ALS, #FundProperty FP
where ALC.AllocationTypeId = ALS.AllocationTypeId
and ALC.SecurityId = ALS.Id
and ALC.FundId = FP.ParentFundId
and ALC.AllocationTypeId = FP.AllocationTypeId
and ALC.ReportDate = #ReportDate
insert into #Allocations(FundCode,FundName,FundRange,AllocationType,UpdatedSourceName,PositionsName,ISIN,Percentage)
select distinct FP.ParentFundCode, FP.FundName, FP.FundRange, FP.AllocationType, FP.UpdatedSourceName, ALS.Name, ALS.ISIN, ALC.Percentage
from fs.Allocation ALC, fs.AllocationSecurity ALS, #FundProperty FP
where ALC.SecurityId = ALS.Id
and ALC.FundId = FP.ParentFundId
and ALC.AllocationTypeId = FP.AllocationTypeId
and FP.FundRange = 'PRULINK PHILIPPINES'
and ALC.ReportDate = #ReportDate
update #Allocations set PPMAName = PPMA.Merrill_Industry___Level_2
from fs.PPMADataExtract PPMA, #Allocations T
where T.AllocationType = 'Sector'
and T.ISIN = PPMA.ISIN
and PPMA.ReportDate = #ReportDate
/*and case when right(PPMA.as_of_date,3) like '/%' --
then convert(datetime,REPLACE(PPMA.As_Of_Date,right(PPMA.As_Of_Date,3),'/20' + right(PPMA.As_Of_Date,2) ),103)
else convert(datetime,PPMA.As_Of_Date,103) end = #ReportDate --*/
update #Allocations set
SnPRating = PPMA.S_P_Rating,
MoodyRating = PPMA.Moody_Rating
from fs.PPMADataExtract PPMA, #Allocations T
where T.AllocationType = 'Rating'
and T.ISIN = PPMA.ISIN
and PPMA.ReportDate = #ReportDate
/*and case when right(PPMA.as_of_date,3) like '/%' --
then convert(datetime,REPLACE(PPMA.As_Of_Date,right(PPMA.As_Of_Date,3),'/20' + right(PPMA.As_Of_Date,2) ),103)
else convert(datetime,PPMA.As_Of_Date,103) end = #ReportDate --*/
update #Allocations set
PPMAName = CONVERT(date,PPMAName,103),
Maturity =
case when convert(float,datediff(day,#ReportDate,convert(date,PPMAName,103)))/365 <= 1 then '0-1 Year'
when convert(float,datediff(day,#ReportDate,convert(date,PPMAName,103)))/365 between 1 and 5 then '1-5 Years'
when convert(float,datediff(day,#ReportDate,convert(date,PPMAName,103)))/365 between 5 and 10 then '5-10 Year'
when convert(float,datediff(day,#ReportDate,convert(date,PPMAName,103)))/365 > 10 then '> 10 Years'
else 'NA'
end
where AllocationType = 'Maturity'
update #Allocations set AssetName = ALS.Name from fs.AllocationSecurity ALS, #Allocations T where T.ISIN = ALS.ISIN
and ALS.AllocationTypeId = 9 and T.FundRange in ('IOF','IOF HK')
--select * from #Allocations
update #Allocations set FundRange = 'IOF SG' where FundRange = 'IOF'
if #Missing = 0
select convert(varchar,#ReportDate,103) [ReportDate], * from #Allocations where
PPMAName is not null
and ISIN <> 'NA'
order by FundName, AllocationType
else
begin
delete from #Allocations where FundRange = 'IOF HK'
select
convert(varchar,#ReportDate,103) [ReportDate],
FundCode,
FundName,
AllocationType,
ISIN,
PositionsName,
Percentage,
PPMAName,
UpdatedSourceName,
AssetName
from #Allocations
where PPMAName is null and SnPRating is null and MoodyRating is null
and ISIN <> 'NA'
order by FundName, AllocationType
end
drop table #Allocations

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

Stored Procedure returning different results with no changes

I have a large stored procedure which contains a cursor and some rounding. When I run the stored procedure and look at the allotment column the number will change by a dollar sometimes without any changes to the SQL code. So I can run the query, check a record and see $10300 a few times then it will switch to $10299 then back etc. It's not consistent across all records either. The records that are accurate or off can be in any combination every time I run the procedure.
Seems completely arbitrary and I've never seen anything like this in all the years I've been working with SQL. My guess is that it's the rounding but I would still expect it to work the same way every time. I'd be grateful for any thoughts or ideas to try. Thank you!
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spGetDatabase]
-- Add the parameters for the stored procedure here
#FY as CHAR(4),
#Obj_det as CHAR(3),
#Agy_Obj as CHAR(2),
#ArchiveId as INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #temp TABLE ( FY CHAR(4),
PCA CHAR(5),
Index_No CHAR(4),
Obj_det CHAR(3),
Agy_obj CHAR(2),
Appro_sym CHAR(3),
Fund_src CHAR(1),
Fund_No CHAR(4),
Method CHAR(1),
Project CHAR(6),
[Char] CHAR(1),
Allotment NUMERIC(14,0))
DECLARE #RecordId as INTEGER,
#CurrentFY CHAR(4),
#CurrentPCA CHAR(5),
#CurrentIndex_No CHAR(4),
#CurrentObj_det CHAR(3),
#CurrentAgy_obj CHAR(2),
#CurrentAppro_sym CHAR(3),
#CurrentFund_src CHAR(1),
#CurrentFund_No CHAR(4),
#CurrentMethod CHAR(1),
#CurrentProject CHAR(6),
#CurrentChar CHAR(1),
#CurrentAllotment NUMERIC(14,0),
#CurrentSumAllotment NUMERIC(14,0),
#CurrentPcainAllotment NUMERIC(14,0),
#PreviousRecordId as INTEGER,
#PreviousFY CHAR(4),
#PreviousPCA CHAR(5),
#PreviousIndex_No CHAR(4),
#PreviousObj_det CHAR(3),
#PreviousAgy_obj CHAR(2),
#PreviousFund_src CHAR(1),
#PreviousFund_No CHAR(4),
#PreviousMethod CHAR(1),
#PreviousProject CHAR(6),
#PreviousChar CHAR(1),
#PreviousAllotment NUMERIC(14,0),
#PreviousSumAllotment NUMERIC(14,0),
#PreviousPcainAllotment NUMERIC(14,0),
#getUplfile CURSOR
SET #getUplfile = CURSOR FOR
SELECT (ROW_NUMBER()
OVER (ORDER BY FY,
PCA,
Index_No,
Obj_Det,
Agy_Obj) )as RowNumber,
FY,
PCA,
Index_No,
obj_det,
agy_obj,
Appro_sym,
Fund_src,
Fund_No,
Method,
Project,
[Char],
Allotment,
SumAllotment,
PcainAllotment
FROM (SELECT a.fy,
a.pca,
a.index_no,
a.obj_det,
a.agy_obj,
a.appro_sym,
a.fund_src,
a.fund_no,
a.method,
a.project,
a.[char],
a.ALLOTMENT,
c.allotment as SumAllotment,
b.Allotment as PcainAllotment
FROM (SELECT tblpcain.fy,
tblpcain.pca,
tblpcain.index_no,
tblpcain.obj_det,
tblpcain.agy_obj,
tblpcafl.appro_sym,
tblpcafl.fund_src,
tblpcafl.fund_no,
tblpcafl.method,
tblpcafl.project,
tblappro.[char],
ROUND(SUM(CASE
WHEN tblpcain.obj_det = #Obj_det AND
tblpcain.agy_obj = #Agy_Obj AND
tblpcain.pca between '05000' AND '05999' THEN CASE
WHEN tblpcafl.fund_src = 'F' THEN tblpcain.allotment * tblpcafl.W_PNCT
ELSE 0
END
ELSE tblpcain.allotment * tblpcafl.pnct
END),2) as Allotment
FROM tblpcain,
tblpcafl,tblappro
WHERE tblpcain.fy + tblpcain.pca = tblpcafl.fy + tblpcafl.pca AND
tblpcafl.fy + tblpcafl.appro_sym = tblappro.fy + tblappro.appro_sym AND
tblpcain.fy = #FY AND
tblpcain.archiveid = #ArchiveId AND
tblpcafl.archiveid = #ArchiveId AND
tblappro.archiveid = #ArchiveId
GROUP BY tblpcain.fy,
tblpcain.pca,
tblpcain.index_no,
tblpcain.obj_det,
tblpcain.agy_obj,
tblpcafl.appro_sym,
tblpcafl.fund_src,
tblpcafl.fund_no,
tblpcafl.method,
tblpcafl.project,
tblappro.[char]) as a LEFT JOIN
tblpcain as b ON a.fy = b.fy AND a.index_no = b.index_no AND a.pca = b.pca AND a.obj_det = b.obj_det AND a.agy_obj = b.agy_obj LEFT JOIN
(SELECT fy,
pca,
index_no,
obj_det,
agy_obj,
SUM(allotment) as allotment
FROM (SELECT tblpcain.fy,
tblpcain.pca,
tblpcain.index_no,
tblpcain.obj_det,
tblpcain.agy_obj,
tblpcafl.appro_sym,
tblpcafl.fund_src,
tblpcafl.fund_no,
tblpcafl.method,
tblpcafl.project,
tblappro.[char],
SUM(ROUND(CASE
WHEN tblpcain.obj_det = #Obj_Det AND
tblpcain.agy_obj = #Agy_Obj AND
tblpcain.pca between '05000' AND '05999' THEN CASE
WHEN tblpcafl.fund_src = 'F' THEN tblpcain.allotment * tblpcafl.W_PNCT
ELSE 0
END
ELSE tblpcain.allotment * tblpcafl.pnct
END,0)) as Allotment
FROM tblpcain,
tblpcafl,tblappro
WHERE tblpcain.fy + tblpcain.pca = tblpcafl.fy + tblpcafl.pca AND
tblpcafl.fy + tblpcafl.appro_sym = tblappro.fy + tblappro.appro_sym AND
tblpcain.fy = #Fy AND
tblpcain.archiveid = #ArchiveId AND
tblpcafl.archiveid = #ArchiveId AND
tblappro.archiveid = #ArchiveId
GROUP BY tblpcain.fy,
tblpcain.pca,
tblpcain.index_no,
tblpcain.obj_det,
tblpcain.agy_obj,
tblpcafl.appro_sym,
tblpcafl.fund_src,
tblpcafl.fund_no,
tblpcafl.method,
tblpcafl.project,
tblappro.[char]) as MyData
GROUP BY fy,
pca,
index_no,
obj_det,
agy_obj) as c ON a.fy = c.fy AND a.index_no = c.index_no AND a.pca = c.pca AND a.obj_det = c.obj_det AND a.agy_obj = c.agy_obj) As Data
OPEN #getUplfile
FETCH NEXT FROM #getUplfile
INTO #RecordId,
#CurrentFY,
#CurrentPCA,
#CurrentIndex_No,
#CurrentObj_det,
#CurrentAgy_obj,
#CurrentAppro_sym,
#CurrentFund_src,
#CurrentFund_No,
#CurrentMethod,
#CurrentProject,
#CurrentChar,
#CurrentAllotment,
#CurrentSumAllotment,
#CurrentPcainAllotment
WHILE ##FETCH_STATUS = 0
BEGIN
If #CurrentSumAllotment <> #CurrentPcainallotment AND
(#CurrentFY <> #PreviousFY OR
#CurrentPCA <> #PreviousPCA OR
#CurrentIndex_No <> #PreviousIndex_No OR
#CurrentObj_Det <> #PreviousObj_Det OR
#CurrentAgy_Obj <> #PreviousAgy_Obj)
BEGIN
SET #CurrentAllotment = #CurrentAllotment + (#CurrentPcainAllotment - #CurrentSumAllotment)
END
SET #PreviousFY = #CurrentFY
SET #PreviousPCA = #CurrentPCA
SET #PreviousIndex_No = #CurrentIndex_No
SET #PreviousObj_det = #CurrentObj_Det
SET #PreviousAgy_obj = #Currentagy_obj
INSERT INTO #Temp ( FY,
PCA,
Index_No,
Obj_det,
Agy_obj,
Appro_sym,
Fund_src,
Fund_No,
Method,
Project,
[Char],
Allotment)
SELECT #CurrentFY,
#CurrentPCA,
#CurrentIndex_No,
#CurrentObj_det,
#CurrentAgy_obj,
#CurrentAppro_sym,
#CurrentFund_src,
#CurrentFund_No,
#CurrentMethod,
#CurrentProject,
#CurrentChar,
#CurrentAllotment
FETCH NEXT FROM #getUplfile
INTO #RecordId,
#CurrentFY,
#CurrentPCA,
#CurrentIndex_No,
#CurrentObj_det,
#CurrentAgy_obj,
#CurrentAppro_sym,
#CurrentFund_src,
#CurrentFund_No,
#CurrentMethod,
#CurrentProject,
#CurrentChar,
#CurrentAllotment,
#CurrentSumAllotment,
#CurrentPcainAllotment
END
CLOSE #getUplfile
DEALLOCATE #getUplfile
SELECT FY,
PCA,
Index_No,
Obj_det,
Agy_obj,
Appro_sym,
Fund_src,
Fund_No,
Method,
Project,
[Char],
Allotment
FROM #Temp
ORDER BY FY,
PCA,
Index_no,
Obj_det,
Agy_obj
END

Reset column value everyday

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())

Improve case statement in order clause

I have the store sql
ALTER procedure [dbo].[TNNews_User_SearchBasic]
#Title nvarchar(400),
#CategoryId int,
#IsInterested int,
#IsHot int,
#IsTopCategory int,
#IsPublish int,
#PageSize int,
#PageIndex int,
#OrderBy varchar(20),
#PortalId int,
#LanguageId varchar(6)
as
DECLARE #EndTime DATETIME
DECLARE #StartTime DATETIME
SET #StartTime = GETDATE()
declare #tbCategory table(Id int)
DECLARE #StartRowIndex INT
IF #PageSize=0 SELECT #PageSize=count(*) FROM TNNews
IF(#PageIndex<0) SET #PageIndex=0
SET #StartRowIndex = #PageSize*(#PageIndex-1)+1
;WITH tmpCategory(Id, Name,ParentId,Level)
AS (
SELECT
e.Id,
e.Name,
e.ParentId,
1
FROM dbo.TNCategory AS e
WHERE
Id = #CategoryId or (#CategoryId='' and ParentId<=0)
UNION ALL
SELECT
e.Id,
e.Name,
e.ParentId,
Level + 1
FROM dbo.TNCategory AS e
JOIN tmpCategory AS d ON e.ParentId = d.Id
)
insert #tbCategory select Id from tmpCategory
;WITH tmpNews as
(
SELECT
a.Id,a.Title,a.Subject
,ROW_NUMBER() OVER (ORDER BY (Publisheddate) desc) as ThuTuBanGhi
FROM dbo.TNNews a
where 1 = 1
--and ( Title like '%'+#Title+'%')
and (#CategoryId = -1 or exists (select 0 from #tbCategory b where b.Id = a.CategoryId))
and (#IsInterested = -1 or IsIntrested = #IsInterested )
and (#IsHot = -1 or IsHot = #IsHot )
and (#IsTopCategory = -1 or IsTopCategory = #IsTopCategory )
and (#IsPublish = -1 or IsPublished = #IsPublish)
and PortalId=#PortalId
and LanguageId = #LanguageId
)
select *, (select COUNT(Id) from tmpNews) as 'TongSoBanGhi' from tmpNews
WHERE
ThuTuBanGhi BETWEEN (#StartRowIndex) AND (#StartRowIndex + #PageSize-1)
SET #EndTime = GETDATE()
PRINT 'StartTime = ' + CONVERT(VARCHAR(30),#StartTime,121)
PRINT ' EndTime = ' + CONVERT(VARCHAR(30),#EndTime,121)
PRINT ' Duration = ' + STR(DATEDIFF(MILLISECOND,#StartTime,#EndTime)) + ' millisecond'
select STR(DATEDIFF(MILLISECOND,#StartTime,#EndTime))
After this store excute
EXEC [dbo].[TNNews_User_SearchBasic]
#Title='',
#CategoryId = '',
#IsInterested = -1,
#IsHot = -1,
#IsTopCategory = -1,
#IsPublish = -1,
#PageSize = 20,
#PageIndex = 1,
#OrderBy = '',
#PortalId = 0,
#LanguageId = N'vi-VN'
go
The time excute about "200ms". And I create a new store "TNNews_User_SearchBasic1" with some change.
.....
--,ROW_NUMBER() OVER (ORDER BY (Publisheddate) desc) as ThuTuBanGhi
,ROW_NUMBER() OVER (ORDER BY (case when #OrderBy='VIEW_COUNT' then ViewCount else PublishedDate end) desc) as ThuTuBanGhi
.....
and now the time excute this store
EXEC [dbo].[TNNews_User_SearchBasic1]
#Title='',
#CategoryId = '',
#IsInterested = -1,
#IsHot = -1,
#IsTopCategory = -1,
#IsPublish = -1,
#PageSize = 20,
#PageIndex = 1,
#OrderBy = '',
#PortalId = 0,
#LanguageId = N'vi-VN'
GO
about 900ms.
I don't understand why there is a change. Please help me improve these stores.
PS: I put example db at: http://anhquan22.tk/Portals/0/Videos/web.rar
Finished analysis the structure of your database. The part of the problem is hiding in the table structure.
I have prepared a backup for you. In it, I slightly modified scheme to improve performance and some normalize the table. You can download it from this link.
...to your question, I would do like this -
DECLARE #SQL NVARCHAR(1000)
SELECT #SQL = N'
;WITH tmpCategory (Id, Name, ParentId, [Level]) AS
(
SELECT
e.Id
, e.Name
, e.ParentId
, 1
FROM dbo.TNCategory e
WHERE Id = #CategoryId OR (#CategoryId = '''' AND ParentId <= 0)
UNION ALL
SELECT
e.Id
, e.Name
, e.ParentId
, [Level] + 1
FROM dbo.TNCategory e
JOIN tmpCategory d ON e.ParentId = d.Id
)
SELECT
a.Id
, ROW_NUMBER() OVER (ORDER BY ' +
CASE WHEN #OrderBy = 'VIEW_COUNT'
THEN 'ViewCount'
ELSE 'PublishedDate'
END +' DESC) AS ThuTuBanGhi
FROM dbo.TNNewsMain a
where PortalId = #PortalId
AND LanguageId = #LanguageId'
+ CASE WHEN #IsInterested != -1 THEN ' AND IsInterested = #IsInterested' ELSE '' END
+ CASE WHEN #IsHot != -1 THEN ' AND IsHot = #IsHot' ELSE '' END
+ CASE WHEN #IsTopCategory != -1 THEN ' AND IsTopCategory = #IsTopCategory' ELSE '' END
+ CASE WHEN #IsPublish != -1 THEN ' AND IsPublish = #IsPublish' ELSE '' END
+ CASE WHEN #CategoryId != -1 THEN '' ELSE ' AND EXISTS(SELECT 1 FROM tmpCategory b WHERE b.Id = a.CategoryId)' END
INSERT INTO #temp (Id, ThuTuBanGhi)
EXECUTE sp_executesql
#SQL
, N'#PortalId INT
, #LanguageId VARCHAR(6)
, #CategoryId INT
, #IsInterested INT
, #IsHot INT
, #IsTopCategory INT
, #IsPublish INT'
, #PortalId = #PortalId
, #LanguageId = #LanguageId
, #CategoryId = #CategoryId
, #IsInterested = #IsInterested
, #IsHot = #IsHot
, #IsTopCategory = #IsTopCategory
, #IsPublish = #IsPublish;
SELECT
d.Id
, tm.Title
, tm.[Subject]
, d.ThuTuBanGhi
, c.TongSoBanGhi
FROM (
SELECT t.Id
, t.ThuTuBanGhi
FROM #temp t
WHERE t.ThuTuBanGhi BETWEEN #StartRowIndex AND #StartRowIndex + #PageSize - 1
) d
JOIN TNNewsMain tm ON d.Id = tm.Id
CROSS JOIN (
SELECT TongSoBanGhi = (SELECT COUNT(1) FROM #temp)
) c

Error converting data type varchar to numeric in SQL

I have spent the last 3 hours trying to figure this out but I have had not luck. When executing this SP I get the below error:
Msg 8114, Level 16, State 5, Procedure sp_SPLIT_CARTON, Line 28
Error converting data type varchar to numeric.
Here is the SP and help is really appreciated
USE [1_WMS]
GO
ALTER PROCEDURE [dbo].sp_SPLIT_CARTON
#FROM_CARTON VARCHAR(20)
, #TO_CARTON VARCHAR(20)
, #SKU VARCHAR(20)
, #QTY DECIMAL
, #USER VARCHAR(20)
AS
DECLARE
#DATE VARCHAR(10)
, #TIME VARCHAR(8)
, #SYS_CONFIG_CODE VARCHAR(5)
, #SYS_CONFIG_VALUE INT
, #CN_STATUS INT
, #CN_STATUS_1 INT --USE FOR BETWEEN STATEMENT
, #CN_STATUS_2 INT --USE FOR BETWEEN STATEMENT
, #CN_STORE VARCHAR(10)
SET #DATE = CONVERT(VARCHAR(10), GETDATE(),101);
SET #TIME = CONVERT(VARCHAR(8), GETDATE(),114);
SET #SYS_CONFIG_CODE = 'SPLCN';
SET #CN_STATUS_1 = '10';
--SET #CN_STATUS_2 = 20;
--THIS IS LINE 28
/*CHECK FOR VALID CARTON STATUS BEFORE SPLITTING*/
SELECT #CN_STATUS = cn_status
, #CN_STORE = cn_store
FROM CARTON
WHERE cn_number = #FROM_CARTON --I BELIEVE THIS IS THE PIECE OF CODE CAUSING THE ISSUE
IF #CN_STATUS = #CN_STATUS_1
BEGIN
/*CHECK FOR SYSTEM CONFIGURATION*/
SELECT #SYS_CONFIG_VALUE = sys_value FROM SYS_CONFIG
WHERE sys_code = #SYS_CONFIG_CODE
IF #SYS_CONFIG_VALUE = 1
BEGIN
/*REMOVE SKU FROM CURRENT CARTON*/
DELETE FROM CARTON_DETAIL
WHERE cd_carton_number = #FROM_CARTON
AND cd_barcode = #SKU
/*UPDATE THE CARTON HEADER*/
UPDATE CARTON
SET cn_packed_qty = cn_packed_qty - #QTY
, cn_modify_date = #DATE
, cn_modify_time = #TIME
, cn_modify_by = #USER
WHERE cn_number = #FROM_CARTON
AND cn_status BETWEEN #CN_STATUS_1 AND #CN_STATUS_2
/*CREATE NEW CARTON HEADER*/
INSERT INTO CARTON
(
cn_number
)
VALUES
(
#FROM_CARTON
)
/*CREATE CARTON DETAIL*/
INSERT INTO CARTON_DETAIL
(
cd_carton_number
)
VALUES
(
#TO_CARTON
)
END
ELSE IF #SYS_CONFIG_VALUE = 0
BEGIN
/*REMOVE SKU FROM CURRENT CARTON*/
DELETE FROM CARTON_DETAIL
WHERE cd_carton_number = #FROM_CARTON
AND cd_barcode = #SKU
/*UPDATE THE CARTON HEADER*/
UPDATE CARTON
SET cn_packed_qty = cn_packed_qty - #QTY
, cn_modify_date = #DATE
, cn_modify_time = #TIME
, cn_modify_by = #USER
WHERE cn_number = #FROM_CARTON
AND cn_status BETWEEN #CN_STATUS_1 AND #CN_STATUS_2
/*GET THE NEXT CARTON FROM COUNTERS*/
SELECT #TO_CARTON = counter_current FROM COUNTERS WHERE counter_name = (
SELECT DISTINCT so_counter_name FROM STORES WHERE SO_NUMBER = (
SELECT DISTINCT cn_store FROM CARTON WHERE cn_number = #FROM_CARTON))
/*UPDATE THE COUNTER AFTER GETTING THE NEXT CARTON NUMBER*/
UPDATE COUNTERS SET counter_current = counter_current + 1
, counter_next = counter_next + 1
WHERE counter_name = (SELECT DISTINCT so_counter_name FROM STORES WHERE SO_NUMBER = (
SELECT DISTINCT cn_store FROM CARTON WHERE cn_number = #FROM_CARTON))
/*CREATE NEW CARTON HEADER*/
DECLARE
#CN_NUMBER VARCHAR(20) , #CN_PICKTICKET VARCHAR(20) , #2ndCN_STORE VARCHAR(10) , #CN_LOAD_NUMBER VARCHAR(20)
, #CN_SHIPMENT_NUMBER VARCHAR(20) , #CN_MANIFEST_NUMBER VARCHAR(20) , #CN_PACKED_QTY DECIMAL , #CN_TRACKING_NUMBER VARCHAR(20)
, #CN_TYPE VARCHAR(5) , #CN_PACK_TYPE VARCHAR(5) , #CN_ROUTE VARCHAR(5) , #CN_SHIP_VIA VARCHAR(5)
, #CN_BOL VARCHAR(20) , #CN_MBOL VARCHAR(20) , #CN_PARCEL_NUMBER VARCHAR(10) , #CN_TRAILER_NUMBER VARCHAR(10)
, #CN_AREA VARCHAR(10) , #CN_ZONE VARCHAR(10) , #CN_AISLE VARCHAR(10) , #CN_LEVEL VARCHAR(10)
, #CN_POSITION VARCHAR(10) , #CN_HEIGHT DECIMAL , #CN_WIDTH DECIMAL , #CN_DIMENSION DECIMAL
, #CN_WEIGHT DECIMAL , #CN_VOLUME DECIMAL , #2ndCN_STATUS INT , #CN_ADDRESS VARCHAR(150)
, #CN_ADDRESS_1 VARCHAR(150) , #CN_CITY VARCHAR(50) , #CN_STATE VARCHAR(50) , #CN_ZIP_CODE VARCHAR(20)
, #CN_COUNTRY VARCHAR(50) , #CN_MISC7 VARCHAR(50) , #CN_MISC8 VARCHAR(50) , #CN_MISC9 VARCHAR(50)
, #CN_MISC10 VARCHAR(50)
SET #CN_NUMBER = #TO_CARTON SET #2ndCN_STORE = #CN_STORE SET #CN_LOAD_NUMBER = ''
SET #CN_SHIPMENT_NUMBER = '' SET #CN_MANIFEST_NUMBER = '' SET #CN_PACKED_QTY = ''
SET #CN_TRACKING_NUMBER = '' SET #CN_TYPE = 'SPLIT' SET #CN_PACK_TYPE = 'SPLITTED'
SET #CN_ROUTE = '' SET #CN_SHIP_VIA = '' SET #CN_BOL = ''
SET #CN_MBOL = '' SET #CN_PARCEL_NUMBER = '' SET #CN_TRAILER_NUMBER = ''
SET #CN_AREA = '' SET #CN_ZONE = '' SET #CN_AISLE = ''
SET #CN_LEVEL = '' SET #CN_POSITION = '' SET #CN_HEIGHT = ''
SET #CN_WIDTH = '' SET #CN_DIMENSION = '' SET #CN_WEIGHT = ''
SET #CN_VOLUME = '' SET #2ndCN_STATUS = '10' SET #CN_MISC7 = ''
SET #CN_MISC8 = '' SET #CN_MISC9 = '' SET #CN_MISC10 = ''
/*GET STORE INFORMATION*/
SELECT #CN_ADDRESS = so_address
, #CN_ADDRESS_1 = so_address_1
, #CN_CITY = so_city
, #CN_STATE = so_state
, #CN_ZIP_CODE = so_zip_code
, #CN_COUNTRY = so_country
FROM STORES
WHERE so_number = #CN_STORE
EXECUTE sp_CREATE_CARTON
#CN_NUMBER , #CN_PICKTICKET , #CN_STORE , #CN_LOAD_NUMBER , #CN_SHIPMENT_NUMBER
, #CN_MANIFEST_NUMBER , #CN_PACKED_QTY , #CN_TRACKING_NUMBER , #CN_TYPE , #CN_PACK_TYPE
, #CN_ROUTE , #CN_SHIP_VIA , #CN_BOL , #CN_MBOL , #CN_PARCEL_NUMBER
, #CN_TRAILER_NUMBER , #CN_AREA , #CN_ZONE , #CN_AISLE , #CN_LEVEL
, #CN_POSITION , #CN_HEIGHT , #CN_WIDTH , #CN_DIMENSION , #CN_WEIGHT
, #CN_VOLUME , #CN_STATUS , #CN_ADDRESS , #CN_ADDRESS_1 , #CN_CITY
, #CN_STATE , #CN_ZIP_CODE , #CN_COUNTRY , #CN_MISC7 , #CN_MISC8
, #CN_MISC9 , #CN_MISC10 , #USER
INSERT INTO CARTON
(
cn_number
)
VALUES
(
#TO_CARTON
)
/*CREATE CARTON DETAIL*/
INSERT INTO CARTON_DETAIL
(
cd_carton_number
)
VALUES
(
#TO_CARTON
)
END
END
--ELSE
-- BEGIN
-- EXECUTE sp_CREATE_ERROR_MESSAGE
-- #ER_TYPE
-- END
GO
--Find the row that is not numeric and fix data
SELECT *
FROM CARTON
WHERE ISNUMERIC(cn_number) != 1 OR
ISNUMERIC(cn_status) != 1
--If you can't fix the data you will need to cast as varchar and compare