Related
I am going nuts and I mean i cannot figure out since so many days what's happening.
Client is using this and inserting data in to the tables.
EQ_HEADER is the table and after puting data into that we take it's PRIMARY key EQ_HEADERID and put in other tables.
But PROBLEM is
In some cases.... the PRIMARY KEY that we get from PARENT table is getting duplicated in the all other child tables even the EQUIPMENTNO is different. It's 1 to 1 only but why HEADERID is getting repeated in many cases?
ALTER PROCEDURE [dbo].[InsertEquipmentsDATA]
#FunctionalLocation varchar(30)= null ,
#EquipmentNo varchar(30) = null ,
#IsGeneralEmpty bit=0,
#ANSDTSpecified bit= null,
#ANSDT_General date= null,
#ANSWT_General varchar(13)= null,
#BAUJJ_General varchar(4)= null,
#BAUMM_General varchar(2)= null,
#BEGRU_General varchar(4)= null,
#EQART_General varchar(10)= null,
#ERDAT_General date= null,
#ERDATSpecified bit= null,
#HERLD_General varchar(3)= null,
#HZEIN_General varchar(30)= null,
#HERST_General varchar(30)= null,
#INBDT_General date= null,
#INBDTSpecified bit= null,
#SERGE_General varchar(30)= null,
#TYPBZ_General varchar(20)= null,
#IsHeaderEmpty bit=0,
#DATAB_Header date= null,
#DATABSpecified bit= null,
#DATABI_Header date= null,
#DATABISpecified bit= null,
#EQTYP varchar(1)= null,
#EQUNR varchar(18)= null,
#GUID_Header varchar(36)= null,
#SHTXT_Header varchar(40)= null,
#STTXT_Header varchar(4)= null,
#IsLocationEmpty bit=0,
#ABCKZ_Location varchar(1)= null,
#BEBER_Location varchar(3)= null,
#EQFNR_Location varchar(30)= null,
#MSGRP_Location varchar(8)= null,
#STORT_Location varchar(10)= null,
#SWERK_Location varchar(4)= null,
#IsOrganizationEmpty bit= 0,
#ANLNR_Organizations varchar(12)= null,
#BUKRS_Organizations varchar(4)= null,
#GEWRK_Organizations varchar(20)= null,
#GSBER_Organizations varchar(4)= null,
#INGRP_Organizations varchar(3)= null,
#IWERK_Organizations varchar(4)= null,
#KOKRS_Organizations varchar(4)= null,
#KOSTL_Organizations varchar(10)= null,
#PROID_Organizations varchar(20)= null,
#RBNR_Organizations varchar(9)= null,
--#ATINN_Classification int,
--#ATWRT_Classification varchar(70),
#IsStructureEmpty bit=0,
#HEQNR_Structure varchar(4)= null,
#HEQUI_Structure varchar(18)= null,
#POSNR_Structure varchar(4)= null,
#SUBMT_Structure varchar(40)= null,
#TIDNR_Structure varchar(25)= null,
#TPLNR_Structure varchar(40)= null,
#ATNAM_Characteristic varchar(50)= null,
#ATZHL_Characteristic varchar(3)= null,
#ATBEZ_Characteristic varchar(40)= null,
#ATWRT_Value varchar(40)= null,
#EINHE_Value varchar(6)= null ,
#ATZHL_Value varchar(3)= null ,
#IsSerialEmpty bit= 0,
#B_CHARGE varchar(10)= null,
#B_LAGER varchar(4)= null,
#B_WERK varchar(4)= null ,
#CHARGE varchar(10) = null ,
#LBBSA varchar(2) = null ,
#MATNR varchar(40) = null ,
#SERNR varchar(18) = null ,
#IsWarrantyEmpty bit= 0,
#GWLDT date= null ,
#GWLDTSpecified bit= null,
#GWLEN date = null ,
#GWLENSpecified bit= null,
#ClassificationCollection Classification readonly,
#CharacteristicCollection Characteristic readonly,
#ValueCollection Value readonly,
#StatusRet varchar(20) out,
#ErrorRet varchar(1000) out
AS
BEGIN
Begin Try
Begin Transaction
Declare #Status Char(1)
SET #Status='N'
IF exists (Select * from EQ_Header where EQUNR= #EQUNR)
Begin
Set #StatusRet= 'Change'
Set #ErrorRet= ''
SET #Status='U'
End
-- --Update EQ_Header
-- --Set
-- -- EquipmentNo = #EquipmentNo ,
-- -- DATAB = #DATAB_Header,
-- -- DATABSpecified = #DATABSpecified ,
-- -- DATBI = #DATABI_Header ,
-- -- DATBISpecified = #DATABISpecified ,
-- -- EQTYP = #EQTYP ,
-- -- EQUNR = #EQUNR ,
-- -- SHTXT = #SHTXT_Header ,
-- -- STTXT = #STTXT_Header
-- --where EQUNR= #EQUNR
-- Set #STATUSRet= 'Change'
-- Set #ErrorRet= (Select ERROR_MESSAGE())
-- Commit
-- return
--End
Insert into FunctionalLocations
(
FunctionalLocation
)
values
(
#FunctionalLocation
)
Insert into [dbo].[Equipment]
(
EquipmentNo,
FunctionalLocation,
Status
)
values
(
#EQUNR,
#FunctionalLocation,
'Pending'
)
IF(#IsHeaderEmpty = 0)
Begin
Insert into [dbo].[EQ_Header]
(
EquipmentNo ,
DATAB ,
DATABSpecified ,
DATBI ,
DATBISpecified ,
EQTYP ,
EQUNR ,
SHTXT ,
STTXT,
GUID,
Status,
Transferred
)
values
(
#EquipmentNo ,
#DATAB_Header ,
#DATABSpecified ,
#DATABI_Header ,
#DATABISpecified ,
#EQTYP ,
#EQUNR ,
#SHTXT_Header,
#STTXT_Header,
#GUID_Header,
#Status,
0
)
End
Declare #HeaderID int
Set #HeaderID= IDENT_CURRENT('EQ_Header') --Latest Header ID
IF(#IsGeneralEmpty = 0)
Begin
Insert into [dbo].[EQ_General]
(
EquipmentNo ,
ANSDT ,
ANSDTSpecified ,
ANSWT ,
BAUJJ ,
BAUMM ,
BEGRU ,
EQART ,
ERDAT ,
ERDATSpecified ,
HERLD ,
HERST ,
HZEIN ,
INBDT ,
INBDTSpecified ,
SERGE ,
TYPBZ ,
HeaderID
)
values
(
#EquipmentNo ,
#ANSDT_General ,
#ANSDTSpecified ,
#ANSWT_General ,
#BAUJJ_General ,
#BAUMM_General ,
#BEGRU_General ,
#EQART_General ,
#ERDAT_General ,
#ERDATSpecified ,
#HERLD_General ,
#HERST_General ,
#HZEIN_General,
#INBDT_General ,
#INBDTSpecified ,
#SERGE_General ,
#TYPBZ_General ,
#HeaderID
)
End
IF(#IsLocationEmpty = 0)
Begin
Insert into [dbo].[EQ_Location]
(
EquipmentNo,
ABCKZ ,
BEBER ,
EQFNR ,
MSGRP ,
STORT ,
SWERK,
HeaderID
)
values
(
#EquipmentNo,
#ABCKZ_Location ,
#BEBER_Location ,
#EQFNR_Location ,
#MSGRP_Location ,
#STORT_Location ,
#SWERK_Location,
#HeaderID
)
End
IF(#IsOrganizationEmpty = 0)
Begin
Insert into [dbo].[EQ_Organizations]
(
EquipmentNo,
ANLNR ,
BUKRS ,
GEWRK ,
GSBER ,
INGRP ,
IWERK ,
KOKRS ,
KOSTL ,
PROID ,
RBNR ,
HeaderID
)
values
(
#EquipmentNo,
#ANLNR_Organizations ,
#BUKRS_Organizations ,
#GEWRK_Organizations ,
#GSBER_Organizations ,
#INGRP_Organizations ,
#IWERK_Organizations ,
#KOKRS_Organizations ,
#KOSTL_Organizations ,
#PROID_Organizations ,
#RBNR_Organizations ,
#HeaderID
)
End
IF(#IsStructureEmpty = 0)
Begin
Insert into [dbo].[EQ_Structure]
(
EquipmentNo,
HEQNR ,
HEQUI ,
POSNR ,
SUBMT ,
TIDNR ,
TPLNR,
HeaderID
)
values
(
#EquipmentNo,
#HEQNR_Structure ,
#HEQUI_Structure ,
#POSNR_Structure ,
#SUBMT_Structure ,
#TIDNR_Structure ,
#TPLNR_Structure,
#HeaderID
)
End
IF(#IsSerialEmpty = 0)
Begin
Insert into [dbo].[EQ_Serial]
(
B_CHARGE,
B_LAGER ,
B_WERK ,
CHARGE ,
LBBSA ,
MATNR ,
SERNR,
HeaderID
)
values
(
#B_CHARGE,
#B_LAGER ,
#B_WERK ,
#CHARGE ,
#LBBSA ,
#MATNR ,
#SERNR,
#HeaderID
)
End
IF(#IsWarrantyEmpty = 0)
Begin
Insert into [dbo].[EQ_Warranty]
(
EquipmentNo ,
GWLDT ,
GWLDTSpecified ,
GWLEN ,
GWLENSpecified,
HeaderID
)
values
(
#EquipmentNo ,
#GWLDT ,
#GWLDTSpecified ,
#GWLEN ,
#GWLENSpecified,
#HeaderID
)
End
Declare #ClassificationTypeCount int
Set #ClassificationTypeCount= (Select Count(*) from #ClassificationCollection)
If(#ClassificationTypeCount > 0)
Begin
--Classification
Insert into [dbo].Eq_Classification
(
EquipmentNo,
CLASS,
KLTXT,
KLART,
HeaderID
)
--values
--(
-- #EquipmentNo,
-- #CLASS_Classification,
-- #KLTXT_Classification,
-- #KLART_Classification
--)
Select #EquipmentNo, CLASS, KLTXT, KLART, #HeaderID from #ClassificationCollection
Declare #ClassificationID int
Set #ClassificationID= IDENT_CURRENT('Eq_Classification')
END
--Characteristic
Declare #CharacteristicTypeCount int
Set #CharacteristicTypeCount= (Select Count(*) from #CharacteristicCollection)
If(#CharacteristicTypeCount > 0)
Begin
Insert into [dbo].EQ_Characteristic
(
EquipmentNo,
ATNAM,
ATZHL,
ATBEZ,
HeaderID,
ClassificationID
)
--values
--(
-- #ATNAM_Characteristic,
-- #ATZHL_Characteristic,
-- #ATBEZ_Characteristic
--)
Select #EquipmentNo , ATNAM, ATZHL, ATBEZ, #HeaderID, #ClassificationID from #CharacteristicCollection
END
--Value
Declare #ValueTypeCount int
Set #ValueTypeCount= (Select Count(*) from #ValueCollection)
If(#ValueTypeCount > 0)
Begin
Insert into [dbo].EQ_Value
(
EquipmentNo,
ATWRT,
EINHE,
ATZHL,
HeaderID,
ClassificationID
)
--values
--(
-- #EquipmentNo,
-- #ATWRT_Value,
-- #EINHE_Value,
-- #ATZHL_Value
--)
Select #EquipmentNo, ATWRT, EINHE, ATZHL, #HeaderID, #ClassificationID from #ValueCollection
End
IF(ISNULL(#StatusRet , '') = '')
Begin
Set #STATUSRet= 'Created'
Set #ErrorRet= ''
End
Commit Transaction
End Try
Begin Catch
Set #STATUSRet= 'Failed'
Set #ErrorRet= ( Select CAST(Error_Line() as Varchar(20)) + ':' +ERROR_MESSAGE())
Rollback Transaction
End Catch
END
I would suggest using SCOPE_IDENTITY rather than IDENT_CURRENT. SCOPE_IDENTITY will give you the latest identity value inserted for the current session and current scope. Whereas IDENT_CURRENT will give you the value from the table across all sessions. If you have multiple clients calling this procedure concurrently it's possible that you could pick up the identity value from a different client.
I'm afraid your sproc is too long to totally parse like this, but I suspect that if this problem is intermittent, then you might find that the error is to do with this line:
Set #HeaderID= IDENT_CURRENT('EQ_Header') --Latest Header ID
You should probably read this:
https://learn.microsoft.com/en-us/sql/t-sql/functions/ident-current-transact-sql?view=sql-server-ver15
And specifically this section:
IDENT_CURRENT is similar to the SQL Server 2000 (8.x) identity
functions SCOPE_IDENTITY and ##IDENTITY. All three functions return
last-generated identity values. However, the scope and session on
which last is defined in each of these functions differ:
IDENT_CURRENT returns the last identity value generated for a specific
table in any session and any scope.
##IDENTITY returns the last
identity value generated for any table in the current session, across
all scopes.
SCOPE_IDENTITY returns the last identity value generated
for any table in the current session and the current scope.
You are currently getting the last generated ID for that table for any scope and any session. You should probably change it to SCOPE_IDENTITY.
I need to update temp table in sql 2014 but this code seems wrong .
first i select all invoices and its Qty from invoices and set Inventory Qty with 0. and second statement i need to update each line by qty of inventory to compare later and use this code.declare #DifferenceTable table (
DataAreaId nvarchar(10) ,
SalesId nvarchar(50) ,
InvoiceId nvarchar(50) ,
ItemId nvarchar(50),
InvoiceQty decimal(16,4) ,
InventoryQty decimal(16,4)
)
insert into #DifferenceTable (DataAreaId , SalesId , InvoiceId , ItemId , InvoiceQty , InventoryQty )
select CustInvoiceTrans.DATAAREAID , CustInvoiceTrans.SALESID , CustInvoiceTrans.INVOICEID , CustInvoiceTrans.ITEMID , sum(CustInvoiceTrans.QTY) , 0. as InventoryQty
from CustInvoiceTrans with(nolock)
group by CustInvoiceTrans.DATAAREAID , CustInvoiceTrans.SALESID , CustInvoiceTrans.INVOICEID , CustInvoiceTrans.ITEMID
update #DifferenceTable
set InventoryQty = tt.Qty from
(select sum(InventTrans.QTY)*-1 as Qty , InventTransOrigin.DATAAREAID , REFERENCEID , InventTrans.INVOICEID , InventTrans.ITEMID
from InventTransOrigin
left join InventTrans on InventTrans.INVENTTRANSORIGIN = InventTransOrigin.RECID
and InventTrans.DATAAREAID = InventTransOrigin.DATAAREAID
and InventTrans.ITEMID = InventTransOrigin.ITEMID
where REFERENCECATEGORY = 0
group by InventTransOrigin.DATAAREAID , REFERENCEID , InventTrans.INVOICEID , InventTrans.ITEMID
) tt
where #DifferenceTable.DataAreaId = tt.DATAAREAID and #DifferenceTable.SalesId = tt.REFERENCEID
and tt.INVOICEID = #DifferenceTable.InvoiceId and tt.ITEMID = #DifferenceTable.ItemId
select * from #DifferenceTable`
I have this stored procedure:
ALTER Procedure [dbo].[sp_Prd_Dashboard_Summary]
(#Period AS INT)
AS
SELECT
SiteName AS SiteName,
MAX(Country) AS Country,
BudgetPrj,
MAX(PeriodEnd) AS PeriodEnd,
MAX(DaysMtd) AS DaysMtd,
MAX(ToGoMtd) AS ToGoMtd,
MAX(PeriodToTDays) AS PeriodToTDays,
SUM(MTDRevenue) AS MtdRev,
SUM(MTDRevenue) / NULLIF(MAX(DaysMTD), 0) * MAX(PeriodToTDays) AS PrjRevenue,
SUM(BdgRevenue) AS BdgRev, SUM(TrgRevenue) AS TrgRev,
SUM(BCMMtd) AS BCMMtd, SUM(HrsMtd) AS HrsMTD,
SUM(FuelVal) AS FuelVal, SUM(FuelLtrs) AS FuelLtrs,
SUM(FuelVal) / NULLIF(SUM(MTDRevenue), 0) AS FuelPerc
FROM
(SELECT
St.SiteName as SiteName,
St.Country as Country,
Null as BudgetPrj, Prd.PeriodEnd as PeriodEnd,
Day(GetDate()) as DaysMtd,
Prd.PeriodNoDays - Day(GetDate()) as ToGoMtd,
Prd.PeriodNoDays as PeriodToTDays,
0 as MTDRevenue, 0 as BdgRevenue,
0 as TrgRevenue, 0 as BCMMtd,
0 as HrsMtd, 0 as FuelVal,
0 as FuelLtrs
FROM
Periods Prd
JOIN
Sites St ON Prd.PeriodSiteID = St.SiteId
WHERE
Prd.Period = #Period AND St.SiteActive = 1
UNION All
Select SiteName as SiteName
, Dit.Country as Country
, Null as BudgetPrj
, Null as PeriodEnd
, 0 DaysMtd
, 0 as ToGoMtd
, 0 as PeriodToTDays
, IIF(Dit.Wcode = 101,
IIF(DiT.WBillMeth = 'Hours', DiT.Hrs * DiT.OpBill,
IIF(DiT.WBillMeth = 'BCM', Loads * DiT.ModelSize * DiT.WBillRate,
IIF(DiT.WBillMeth = 'Cost Plus', (DiT.Hrs * (DiT.OwnBill + DiT.OpBill)) +
(DiT.ShiftHrs * DiT.EmpBill),0))),0) as MTDRevenue
, 0 as BdgRevenue
, 0 as TrgRevenue
, IIF(DiT.WBillMeth = 'BCM', Loads * DiT.ModelSize, 0) as BCMMtd
, IIF(Dit.Wcode = 101,
IIF(DiT.WBillMeth <> 'BCM', DiT.Hrs, 0),0) as HrsMtd
, DiT.Fuel * DiT.FuelRate as FuelVal
, DiT.Fuel as FuelLtrs
From DataInputTotal DiT
Where DiT.Period = #Period and DiT.SiteActive = 1
Union All
Select SiteName as SiteName
, St.Country as Country
, Bdgt.BudgetProject as BudgetPrj
, Prd.PeriodEnd as PeriodEnd
, 0 as DaysMtd
, 0 as ToGoMtd
, 0 as PeriodToTDays
, 0 as MTDRevenue
, PrjRev as BdgRevenue
, BudgTarget as TrgRevenue
, 0 as BCMMtd
, 0 as HrsMtd
, 0 as FuelVal
, 0 as FuelLtrs
From Budget Bdgt Join
Sites St on Bdgt.SiteId = St.SiteId Join
Periods Prd on Bdgt.Period = prd.Period and Bdgt.SiteId = Prd.PeriodSiteID
Where Bdgt.Period = #Period and St.SiteActive = 1
) a
Group By SiteName, BudgetPrj
I am trying to call the procedure and insert the result into a temp table with the below script:
Declare #Period int = 22
Declare #DaysinMonth Int = 29
Declare #DayHrs Int = 24
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
Create Table #Temp (SiteName nvarchar(50)
, Country nvarchar(50)
, BudgetPrj nvarchar(50)
, PeriodEnd DateTime
, DaysMtd Int
, ToGoMtd Int
, PeriodToTDays Int
, MtdRev Numeric(13,2)
, PrjRevenue Numeric(13,2)
, BdgRev Numeric(13,2)
, TrgRev Numeric(13,2)
, BCMMtd Numeric(13,2)
, HrsMtd Numeric(13,2)
, FuelVal Numeric(13,2)
, FuelLtrs Numeric(13,2)
, FuelPerc Numeric(13,2)
, FltCnt Int
, Availibility Numeric(13,2)
, Utilization Numeric(13,2)
, Idle Numeric(13,2)
)
Insert #temp
Exec sp_Prd_Dashboard_Summary #Period
Insert into #temp
Exec summary_fleet_performance #DayHrs, #Period, #DaysinMonth
When running the script I get the following error:
Column name or number of supplied values does not match table definition.
I have checked the aliases of the SELECT and all columns have names.
I ended creating two temp tables and inserting each stored procedure into each table and then joining them.
It worked perfectly for me:
ALTER Procedure [dbo].[summary_dashboard]
(
#Period int,
#DaysinMonth Int,
#DayHrs Int
)
as
Declare #Tbl1 as table (SiteName nvarchar(50) null
, Country nvarchar(50) null
, BudgetPrj nvarchar(50) null
, PeriodEnd DateTime null
, DaysMtd Int null
, ToGoMtd Int null
, PeriodToTDays Int null
, MtdRev Numeric(13,2) null
, PrjRevenue Numeric(13,2) null
, BdgRev Numeric(13,2) null
, TrgRev Numeric(13,2) null
, BCMMtd Numeric(13,2) null
, HrsMtd Numeric(13,2) null
, FuelVal Numeric(13,2) null
, FuelLtrs Numeric(13,2) null
, FuelPerc Numeric(13,2) null
)
Declare #Tbl2 as Table (SiteName nvarchar(50) null
, FltCnt Int null
, Availability Numeric (5,2) null
, Utilization Numeric (5,2) Null
, Idle Numeric(5,2)
)
insert into #Tbl1 (SiteName
, Country
, BudgetPrj
, PeriodEnd
, DaysMtd
, ToGoMtd
, PeriodToTDays
, MtdRev
, PrjRevenue
, BdgRev
, TrgRev
, BCMMtd
, HrsMtd
, FuelVal
, FuelLtrs
, FuelPerc
)
Exec sp_Prd_Dashboard_Summary #Period
insert into #tbl2 (SiteName
, FltCnt
, Availability
, Utilization
, Idle
)
Exec summary_fleet_performance #DayHrs, #Period, #DaysinMonth
select tbl1.SiteName
, tbl1.Country
, tbl1.BudgetPrj
, tbl1.PeriodEnd
, tbl1.DaysMtd
, tbl1.ToGoMtd
, tbl1.PeriodToTDays
, tbl1.MtdRev
, tbl1.PrjRevenue
, tbl1.BdgRev
, tbl1.TrgRev
, tbl1.BCMMtd
, tbl1.HrsMtd
, tbl1.FuelVal
, tbl1.FuelLtrs
, tbl1.FuelPerc
, tbl2.FltCnt
, tbl2.Availability
, tbl2.Utilization
, tbl2.Idle
from #tbl1 tbl1 full outer join
#tbl2 tbl2
on tbl1.SiteName = tbl2.SiteName
TRY THIS: Your stored procedure is returning 14 columns and temporary table has more than that so you have to mention columnS in the INSERT INTO #TEMP as below and if you are not specifying the columns name of table then returning columns from the STORED PROCEDURE also must be same.
INSERT INTO #temp(SiteName
, Country
, BudgetPrj
, PeriodEnd
, DaysMtd
, ToGoMtd
, PeriodToTDays
, MtdRev
, PrjRevenue
, BdgRev
, TrgRev
, BCMMtd
, HrsMtd
, FuelVal
, FuelLtrs)
Exec sp_Prd_Dashboard_Summary #Period
The temporary table to which you are trying to insert rows contains more columns than the result from stored procedure. Provide column names in insert query, like this:
Insert into table(Column1, Column2....)
I have the following query:
INSERT INTO dbo.ResourceOrderCustomersOrders
( OrderId ,
Type ,
CustomerId ,
ResourceId ,
Quantity ,
Created ,
CreatedBy
)
VALUES ( ( SELECT MAX(OrderId) + 1
FROM dbo.ResourceOrderCustomersOrders
) , -- OrderId - int
'PENDING' , -- Type - varchar(50)
( SELECT MAX(CustomerId)
FROM dbo.ResourceOrderCustomers
WHERE UPPER(FirstName) = UPPER(#Firstname)
AND UPPER(Surname) = UPPER(#Surname)
AND UPPER(Email) = UPPER(#Email)
) , -- CustomerId - int
( SELECT MAX(ResourceId)
FROM dbo.ResourceOrderFormContent
WHERE DisplayTitle = #ResourceName
) , -- ResourceId - int
#ResourceQuantity ,
GETDATE() , -- Created - datetime
'WebsiteForm' -- CreatedBy - varchar(20)
);
In cases where a subquery fails I'd like to default to a value of my choosing (to hold unspecified records).
For example, were the following to fail to retrieve a result because a record doesn't exist:
SELECT MAX(ResourceId)
FROM dbo.ResourceOrderFormContent
WHERE DisplayTitle = #ResourceName
Then I would want to return the number '999' (unspecified record). What would be the best way to approach this?
I've tried to use try / catch but I'm being told this is invalid syntax. Here is my attempt:
INSERT INTO dbo.ResourceOrderCustomersOrders
( OrderId ,
Type ,
CustomerId ,
ResourceId ,
Quantity ,
Created ,
CreatedBy
)
VALUES ( ( SELECT MAX(OrderId) + 1
FROM dbo.ResourceOrderCustomersOrders
) , -- OrderId - int
'PENDING' , -- Type - varchar(50)
( SELECT MAX(CustomerId)
FROM dbo.ResourceOrderCustomers
WHERE UPPER(FirstName) = UPPER(#Firstname)
AND UPPER(Surname) = UPPER(#Surname)
AND UPPER(Email) = UPPER(#Email)
) , -- CustomerId - int
( BEGIN TRY
SELECT MAX(ResourceId)
FROM dbo.ResourceOrderFormContent
WHERE DisplayTitle = #ResourceName
END TRY
BEGIN CATCH
SELECT 999
END CATCH
) , -- ResourceId - int
#ResourceQuantity ,
GETDATE() , -- Created - datetime
'WebsiteForm' -- CreatedBy - varchar(20)
);
Max will always return NULL if no rows found. So You can use ISNULL.
SELECT ISNULL(MAX(ResourceId), 999)
FROM dbo.ResourceOrderFormContent
WHERE DisplayTitle = #ResourceName
I am reading a text file as an input to execute the logic in my stored procedure following is the sample of my textfile
<tblThreatenedSpeciesSubzone>
<ThreatenedSpeciesZoneID>-1</ThreatenedSpeciesZoneID>
<ManagementZoneID>0</ManagementZoneID>
<TSSubZoneNumber>BR101_Moderate/Good_Medium_1</TSSubZoneNumber>
<TSSubZoneArea>0</TSSubZoneArea>
<AdjacentRemnantVegArea>23</AdjacentRemnantVegArea>
<PatchArea>0</PatchArea>
<CreatedBySystemUser>BBCC Training 1</CreatedBySystemUser>
<UpdatedBySystemUser>BBCC Training 1</UpdatedBySystemUser>
<SaveType>1</SaveType>
<VegetationZoneID>-1</VegetationZoneID>
<ManagementZoneName />
</tblThreatenedSpeciesSubzone>
If you noticed <ManagementZoneName /> don't have any value. In my stored procedure I tried to find if Managementzone has value or not but not sure is the right way to do
IF #ManagementZoneIDInXML > 0 and ##ManagementZoneIDInXML <> NULL
BEGIN
INSERT INTO #tblThreatenedSpeciesSubzone
(ThreatenedSpeciesZoneID,
ManagementZoneID,
VegetationZoneID,
TSSubZoneNumber,
TSSubZoneArea,
AdjacentRemnantVegArea,
PatchArea,
DateCreated,
CreatedBySystemUser,
DateUpdated,
UpdatedBySystemUser,
SaveType,
RowTimestamp)
SELECT *
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH (ThreatenedSpeciesZoneID INT,
ManagementZoneID INT,
VegetationZoneID INT,
TSSubZoneNumber VARCHAR(50),
TSSubZoneArea NUMERIC(9,2),
AdjacentRemnantVegArea NUMERIC(9,2),
PatchArea NUMERIC(9,2),
DateCreated VARCHAR(50),
CreatedBySystemUser VARCHAR(50),
DateUpdated VARCHAR(50),
UpdatedBySystemUser VARCHAR(50),
SaveType INT,
RowTimestamp VARCHAR(50)) XMLDATA
WHERE
ManagementZoneID = #ManagementZoneIDInXML --Only select the rows that belong to the supplied ManagementZoneID
END
ELSE
BEGIN
INSERT INTO #tblThreatenedSpeciesSubzone
( ThreatenedSpeciesZoneID ,
ManagementZoneID ,
VegetationZoneID ,
TSSubZoneNumber ,
TSSubZoneArea ,
AdjacentRemnantVegArea ,
PatchArea ,
DateCreated ,
CreatedBySystemUser ,
DateUpdated ,
UpdatedBySystemUser ,
SaveType ,
RowTimestamp )
SELECT * FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH ( ThreatenedSpeciesZoneID INT ,
ManagementZoneID INT ,
VegetationZoneID INT ,
TSSubZoneNumber VARCHAR(50) ,
TSSubZoneArea NUMERIC(9,2) ,
AdjacentRemnantVegArea NUMERIC(9,2) ,
PatchArea NUMERIC(9,2) ,
DateCreated VARCHAR(50) ,
CreatedBySystemUser VARCHAR(50) ,
DateUpdated VARCHAR(50) ,
UpdatedBySystemUser VARCHAR(50) ,
SaveType INT ,
RowTimestamp VARCHAR(50) ) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML --Only select the rows that belong to the supplied VegetationZoneID
--And no Management zone assigned
END