SQL query stored procedure - sql-server

Create a stored procedure that passes in the SalesOrderID as a parameter.
This stored procedure will return the SalesOrderID, Date of the transaction, shipping date, city and state. It is not running
Ans:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int,
#SalesOrderOut int OUTPUT,
#OrderDate datetime OUTPUT,
#ShipDate datetime OUTPUT,
#CityState varchar(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #SalesOrderOut = #SalesOrderID
SET #OrderDate = (SELECT OrderDate FROM SALES.SalesOrderHeader )
SET #ShipDate = (SELECT ShipDate FROM Sales.SalesOrderHeader)
SET #CityState = (SELECT a.City, st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID = st.TerritoryID
WHERE SalesOrderID = #SalesOrderID)
END
DECLARE #OrderNum int, #Date datetime, #qty1 int, #Date1 datetime
EXEC proc_findProductInfo 63936,
#SalesOrderOut = #OrderNum OUTPUT,
#OrderDate = #Date OUTPUT,
#ShipDate = #date1,
#CityState = #qty1 output
SELECT #OrderNum, #date, #qty1, #Date1
Error Message:
Msg 116, Level 16, State 1, Procedure proc_findProductInfo, Line 25
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS

You're making this way harder than it needs to be:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int
AS
BEGIN
SET NOCOUNT ON;
SELECT s.SalesOrderID, s.OrderDate, s.ShipDate, a.City,st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID=st.TerritoryID
WHERE s.SalesOrderID = #SalesOrderID
END
I'm not even sure you need the StateProvince table here... the question probably allows you to trust the Address record.

It is complaining about the following
SET #CityState = (
SELECT a.City,st.Name
You are selecting both City and State Name and trying to assign it to a variable.
You either need to concatenate or coalesce them into them into a single output or alternatively use the below type of select to assign each one to a variable.
select
#var1 = field1,
#var2 = field2,
...
As below
SET #SalesOrderOut = #SalesOrderID
SELECT #OrderDate = s.OrderDate,
#ShipDate = s.ShipDate,
#CityState = CONCAT(a.City, ", ", st.Name)
FROM Sales.SalesOrderHeader s
inner JOIN Person.Address a
ON s.ShipToAddressID = a.AddressID
inner JOIN Person.StateProvince st
on s.TerritoryID=st.TerritoryID
WHERE SalesOrderID = #SalesOrderID

Related

Using DECLARE while creating a VIEW?

The literature says that the declare statement is not compatible with creating a View. How do I get around it?
My declare statement looks like:
DECLARE #risk_5 TABLE (Code VARCHAR(100));
INSERT INTO #risk_5 (Code) VALUES ('AA'),('BB'),('CC');
and is then used within a select statement:
SELECT
id,
CASE
WHEN a.[10_2_1_Country] IN (SELECT Code from #risk_5)
THEN '3'
END AS Risk_Country5
FROM x
The recommendation is to pack the declare into a CTE or a stored procedure.
With both these recommendations though, I do not understand how to connect the two? What am I missing?
If you need to use variable try to use stored procedures, if you write a select query in the stored procedure you can get the data too. And you can use declare inside.
I use this way in my solution e.g.
CREATE PROCEDURE [dbo].[GetLoadSiteMass]( #month INT,
#year int,
#storageId int,
#parent nvarchar(50),
#materialSourceId nvarchar(100),
#complexIds nvarchar(50))
AS
BEGIN
DECLARE #MonthPrev int
DECLARE #YearPrev int
SET #MonthPrev = CASE WHEN #Month = 1 THEN 12 ELSE #Month - 1 END
SET #YearPrev = CASE WHEN #Month = 1 THEN #Year - 1 ELSE #Year END
declare #WagonLoadSiteId int
set #WagonLoadSiteId = (select top 1 CarriageLoadSiteId from CarriageLoadSite where LoadSiteType = 2);
DECLARE #loadSide nvarchar(10), #result decimal(18,3)
SET #loadSide=cast( #storageId as nvarchar(50));
WITH CarriageLoadSiteTreeView (
[CarriageLoadSiteId],RootId,RootName,[Code], Name, ParentID, [LoadSiteType],IsDelete,
CodeSAP,DepartmentId, Capacity, MinLimit, MaxLimit, LoadSitePlaceTypeId) AS
(
SELECT [CarriageLoadSiteId],
[CarriageLoadSiteId] RootId,
Name RootName,
[Code],
Name,
ParentID,
[LoadSiteType],
[IsDelete],
CodeSAP,
DepartmentId,
Capacity,
MinLimit,
MaxLimit,
LoadSitePlaceTypeId
FROM CarriageLoadSite WITH(NOLOCK)
WHERE ISNULL(ParentID,0) =isnull(#storageId,0) AND Isdelete!=1
UNION ALL
SELECT d.[CarriageLoadSiteId],
q.RootId RootId,
RootName RootName,
d.[Code],
d.Name,
d.ParentID,
d.[LoadSiteType],
d.[IsDelete],
d.CodeSAP,
d.DepartmentId,
d.Capacity,
d.MinLimit,
d.MaxLimit,
d.LoadSitePlaceTypeId
FROM CarriageLoadSite AS d WITH(NOLOCK)
INNER JOIN CarriageLoadSiteTreeView AS q ON d.ParentID = q.[CarriageLoadSiteId] WHERE d.IsDelete!=1
)
SELECT
ComplexId,
RootId Id,
cast(RootId as nvarchar(8))+'|Sclad'+IIF(RootId=max(R.CarriageLoadSiteId),'|finish','') [Uid],
RootName CarriageLoadSiteName,
ROUND(SUM(AMOUNT-movement-consumption)/1000,3) Amount,
cast(1 as bit) hasChildren,
T.FullPathId Path,
UparentId=IIF(#parent is null,'',#parent),
[Type]=0,
Petal = IIF(RootId=max(R.CarriageLoadSiteId),'|Sclad|finish','')
FROM (
SELECT
RootId
,RootName
,t.CarriageLoadSiteId
,t.MaterialId
,YEAR(t.Period) [Year]
,MONTH(t.Period) [Month]
,round( case when (t.Amount=0 or t.Amount is null) and (tt.Type=0 or [TypeAmountCarriage]=1 )then carr.[CertifNetto]else t.Amount end ,0 )[Amount]
,t.UnitId
, CarriageId
, tt.TurnoverTypeId
,round(dbo.GetMovementByTurnOverWithTempValue(t.turnoverid),5) movement
,dbo.GetConsumptionByTurnOver(t.turnoverid) consumption
,0 stockBegin
,round(t.Amount,0 ) CommingAmount
,case when (t.Amount=0 or t.Amount is null) and tt.Type=0 then 1 else 0 end [IsNotConfirmed]
,[TypeAmountCarriage]
,M.ComplexId
FROM Turnover t WITH(NOLOCK)
INNER JOIN TurnoverType tt ON tt.TurnoverTypeId = t.TurnoverTypeId
INNER JOIN CarriageLoadSiteTreeView l ON l.CarriageLoadSiteId = t.CarriageLoadSiteId
INNER JOIN [Carriages] carr on carr.[CarriagesID]=t.[CarriageId]
INNER JOIN Material M on M.MaterialID=t.MaterialId
WHERE YEAR(t.Period) = #Year AND
MONTH(t.Period) = #Month AND
l.LoadSiteType = 0 AND
tt.type in (0,5,4) AND
isclear=0 AND
M.MaterialSourceID in (select value from string_split(#materialSourceId, ','))
UNION ALL
SELECT RootId
,RootName
,s.CarriageLoadSiteId
,s.MaterialId
,#Year [Year]
,#Month [Month]
,round(s.Amount,0)
,s.UnitId
,CarriageId
,[TurnoverTypeId]
,round(dbo.GetMovementByStock(s.StockId),5) movement
,dbo.GetConsumptionByStock(s.StockId) consumption
,round(s.Amount,0)-s.spendStock
,0
,0 [IsNotConfirmed]
,[TypeAmountCarriage]
,M.ComplexId
FROM Stock s
INNER JOIN CarriageLoadSiteTreeView l ON l.CarriageLoadSiteId = s.CarriageLoadSiteId
INNER JOIN Material M on M.MaterialID=s.MaterialId
WHERE s.[Year] = #YearPrev AND
s.[Month] = #MonthPrev AND
s.[Type] = 0 AND
l.LoadSiteType = 0 AND
amount >0 AND
isclear=0 AND
M.MaterialSourceID in (select value from string_split(#materialSourceId, ','))
) as R
INNER JOIN CariageLoadSiteTree T on T.CarriageLoadSiteId=RootId
INNER JOIN string_split(#complexIds, ',') MM ON CAST(MM.value AS int) = R.ComplexId
WHERE AMOUNT-movement-consumption>10
GROUP BY RootName,RootId,ComplexId, T.FullPathId
ORDER BY RootName

Why I am getting Column Name Missing error

I wrote a SP which will call internally another parameterized SP and output will be store into a physical table.While I am executing Outer SP I am getting following error.
Msg 207, Level 16, State 1, Procedure CBs_LargeExposer, Line 88 [Batch
Start Line 12] Invalid column name 'SlNo'.
I observed, if I execute inner SP in separate window and very next to it if I execute the same outer SP is working fine, after certain time if I execute the same statement(Outer SP) I am getting same error.
ALTER PROCEDURE [dbo].[CBS_GlMapping]
#finYear nvarchar(30)='2019-2020',
#quarter char(5)='Q2',
#Oflag Varchar(6)='O4'
AS
BEGIN
SET NOCOUNT ON;
Declare #QtrStart date,#QtrSEnd date,#FyFrom int,#FyTo int,#BranchId int
select #FyFrom=year(YearBeginDate),#FyTo=Year(YEarEndDate) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
IF(#FyFrom < left(#finYear,4) and #FyTo < Right(#finYear,4))
Begin
print 'Sorry, Recods are not available for the financial year ' + #finYear
return
End
If(#quarter='Q1')
Begin
select #QtrStart=YearBeginDate,#QtrSEnd=EOMONTH(DATEADD(MM,2,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q2')
Begin
select #QtrStart=Dateadd(mm,3,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,5,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q3')
Begin
select #QtrStart=Dateadd(mm,6,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,8,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q4')
Begin
select #QtrStart=DATEADD(month, DATEDIFF(month, 0,Dateadd(mm,-2,YEarEndDate)), 0),#QtrSEnd=YEarEndDate from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
/* To handel the Financial year */
if(left(#finYear,4)<year(#QtrStart) and #quarter<>'Q4')
begin
set #QtrStart = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
if(right(#finYear,4)<year(#QtrStart) and #quarter='Q4')
begin
set #QtrStart = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
Create table #tempData
(
Bal numeric(15,2)
)
declare #sql varchar(500),#sql2 varchar(500),#day Varchar(10),#Month varchar(2),#Year varchar(4)
select #day= Day(#QtrSEnd)
select #Month= month(#QtrSEnd)
select #Year= Year(#QtrSEnd)
Create table #temp
( slno int,
glcode Varchar(500),
GlLen int,
ColNO varchar(50),
CellNo varchar(50),
Amount Numeric(15,2)
)
declare #tsql varchar(500)
set #tsql=N'
insert into #temp
select ROW_NUMBER() over(order by glcode) slno,glcode,LEN(Glcode) GlLen,ColNo,CellNo,amount
from BsGl'+#Oflag+'
where glcode <>'''' '
exec(#tsql)
declare #LoopStart int,#loopEnd Int,#glcode varchar(500),#amt numeric(15,0)
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
while (#LoopStart <= #loopEnd)
begin
select #glcode= Glcode from #temp where slno = #LoopStart
set #sql='insert into #tempData select Sum(day'+#day+') from DayBal where AcYear='+#Year+' and acmonth='+#Month+'and GlCode in(SELECT glcode FROM dbo.splitstring(convert(varchar(500),'''+#glcode+''')))'
EXEC(#sql)
update #temp set Amount=(select Bal from #tempData) where slno =#LoopStart
set #LoopStart=#LoopStart+1
Truncate table #tempData
end
set #tsql=''
set #tsql='update BsGl'+#Oflag+' set Amount=0.00 where Glcode ='''' '
EXEC(#tsql)
set #tsql=''
set #tsql='update B set B.amount=isnull(round((Case when A.Amount<0 then A.Amount*(-1) else A.Amount end/1000),0),0) from #temp a inner join BsGl'+#Oflag+' B on a.CellNo=B.CellNo and B.ColNo=A.ColNo'
EXEC(#tsql)
IF(#Oflag='O4')
BEGIN
EXEC [DBO].[CBs_LargeExposer] #QtrSEnd
END
Drop table #temp
End
Not sure if you have tried this already. Try specifying the exact same column name "slno" as in CREATE TABLE statement, in the below two SELECT statements, instead of "Slno".
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
I found the Solution for the error. I created same #temporary table in outer sp as well as in inner sp with different columns. Basically a #temporary table's scope is limited to the session but when you are calling a inner Sp inside a outer sp it will consider a single session.
Outer SP TempTable Declaration
Create table #tempData
(
Bal numeric(15,2)
)
Inner SP TempTable Declaration
CREATE TABLE #tempData(
[ID] int identity(1,1) ,
[Funded] [numeric](15, 2) NOT NULL,
[NonFunded] [numeric](2, 2) NOT NULL,
[Limitsanctioned] [numeric](15, 2) NOT NULL
)
So I changed the #tmpData to #tempData1 in outer Sp it's working fine.

How to optimise this stored procedure?

I have the stored procedure below and I am having two issues with it
It is running very slowly, and
It is returning a blank result set
The idea for the stored procedure is to do a sequence check to find if any account numbers have not been assigned.
Step 1 loops through all the branches and builds up the tempdetails table.
After that it creates the list of all the numbers that have been used and uses that to delete everything that exists to leave a list of those accountnumbers that do not exist,
But een though I know there are missing account numbers, aside from the exceptionally long tun time it is returning a blank result set.
Anyone have any ideas what is going wrong with it?
Thanks
ALTER PROCEDURE [dbo].[PracticeFindMissingSequenceDetail]
#pracId VARCHAR(128),
#Prefix VARCHAR(256)
AS
BEGIN
DECLARE #TempDetails TABLE (SequenceCheck VARCHAR(24),
Prefix VARCHAR(4),
BranchName VARCHAR(256),
RisStatus VARCHAR(256),
Rislink VARCHAR(256)
);
DECLARE #Branchlist TABLE (BranchId INTEGER,
BranchName VARCHAR(256),
BranchPrefix VARCHAR(4),
PrefixLength INT,
SequenceLength INT
);
DECLARE #TempPatNo TABLE (Patno VARCHAR(24));
DECLARE #BranchName VARCHAR(256),
#BranchPrefix VARCHAR(256),
#PrefixLength INT,
#BranchId INT,
#SequenceLength INT,
#rangestart INTEGER,
#rangeend INTEGER,
#rangenow INTEGER,
#startDate DATETIME,
#Patno VARCHAR(128),
#FormatZeroes VARCHAR(3),
#CurrentLength INT,
#RangeString VARCHAR(256);
INSERT INTO #Branchlist (BranchId, BranchName, BranchPrefix, PrefixLength, SequenceLength)
SELECT
b.id, b.name, b.prefix, PrefixLength, SequenceLength
FROM
Branch b
INNER JOIN
Practice pr ON pr.id = b.practiceid
INNER JOIN
[Sequence] s ON s.id = b.id
WHERE
pr.APIKey = #pracID
AND b.inactive = 0
AND b.prefix = #Prefix
/* insert values for each branch into table*/
DECLARE BranchPointer CURSOR FOR
SELECT BranchID FROM #Branchlist
OPEN BranchPointer
FETCH NEXT FROM BranchPointer INTO #BranchId
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #BranchPrefix = (SELECT BranchPrefix
FROM #Branchlist
WHERE BranchId = #BranchId)
SELECT #PrefixLength = (SELECT PrefixLength
FROM #Branchlist
WHERE BranchId = #BranchId)
SELECT #SequenceLength = (SELEct SequenceLength
FROM #Branchlist
WHERE BranchId = #BranchId)
/* Set the starting date from the sequence */
SELECT #startDate = (SELECT MIN(MinimumSequenceDate)
FROM [Sequence] s
WHERE s.id = #BranchId)
/*get the earliest number in the sequence from the startdate*/
SELECT #rangestart = (SELECT MIN(SUBSTRING(v.bookingnumber, 3, LEN(bookingnumber)))
FROM Visit v
INNER join Branch b ON b.id = v.branchid
INNER join Practice pr ON pr.id = b.practiceid
WHERE pr.APIKey = #pracId
AND LEFT(v.bookingnumber, 2) = #Prefix
AND v.date >= #startDate
AND v.branchid = #BranchId);
/*get the latest number in the sequence from the startdate*/
SELECT #rangeend = (SELECT MAX(SUBSTRING(v.bookingnumber, 3, LEN(bookingnumber)))
FROM Visit v
INNER JOIN Branch b ON b.id = v.branchid
INNER JOIN Practice pr ON pr.id = b.practiceid
WHERE pr.APIKey = #pracId
AND LEFT(v.bookingnumber, 2) = #Prefix
AND v.date >= #startDate
AND v.branchid = #BranchId);
SET #RangeNow = #rangestart
WHILE #rangenow < #rangeend
BEGIN
/*check if leading zeroes are needed in the number and add them if needed*/
SET #RangeString = CAST(#RangeNow AS VARCHAR(256))
SET #CurrentLength = LEN(#rangenow)
IF #prefixlength + #currentlength < #SequenceLength
WHILE #CurrentLength + #PrefixLength < #SequenceLength
BEGIN
SET #RangeString = '0' + #RangeString;
SET #currentlength = LEN(#RangeString);
END;
/*Insert full sequence into temporary table*/
INSERT INTO #TempDetails (SequenceCheck, Prefix, BranchName)
SELECT #Prefix + #RangeString, #Prefix, #BranchName
SET #rangenow =#rangenow+1
END;
FETCH NEXT FROM BranchPointer INTO #BranchName
END
CLOSE BranchPointer
DEALLOCATE BranchPointer
/*delete existing sequence numbers from table*/
INSERT INTO #TempPatNo (PatNo)
SELECT BookingNumber
FROM Visit v1
INNER JOIN Branch b1 ON b1.id = v1.branchid
INNER JOIN Practice pr1 ON pr1.id = b1.practiceid
WHERE pr1.APIKey = #pracId
DELETE #TempDetails
WHERE sequencecheck IN (SELECT patNo FROM #TempPatNo)
/*Insert the status and link for error messages*/
UPDATE #tempDetails
SET RisStatus = (SELECT Status
FROM RISErrors r
INNER JOIN Practice pr ON pr.id = r.PracticeId
WHERE pr.APIKey = #pracId
AND VisitNumber = SequenceCheck
AND r.id = (SELECT MAX(r1.id)
FROM RISErrors r1
INNER JOIN Practice pr1 ON pr1.id = r1.PracticeId
WHERE pr1.APIKey = #pracId
AND VisitNumber = SequenceCheck)),
RisLink = 'http://billing.cryanic.co.za/Clinton/RISErrors?searchquery=' + SequenceCheck
/*return missing numbers into sequence control callong procedure*/
SELECT DISTINCT SequenceCheck, RisStatus, Rislink
FROM #TempDetails
END
After reading your procedure, I made some assumptions:
there is a one-to-one relationsship between sequence and branch
the visits are the details of a sequence
the BranchName and BranchPrefix aren't needed.
I recommend to not do lookups by BranchID but instead retrieve the values from the cursor query. The table BranchList isn't needed, you can base the cursor on the query directly. Also, the TempPatNo table can be avoided.
Here's what I have come up with:
ALTER PROCEDURE [dbo].[PracticeFindMissingSequenceDetail]
#pracId VARCHAR(128),
#Prefix VARCHAR(256)
AS
BEGIN
DECLARE #TempDetails TABLE (
BranchID INT,
SequenceCheck VARCHAR(24),
RisStatus VARCHAR(256),
Rislink VARCHAR(256)
);
DECLARE
#PrefixLength INT,
#BranchId INT,
#SequenceLength INT,
#rangestart INTEGER,
#rangeend INTEGER,
#rangenow INTEGER,
#startDate DATETIME;
/* insert values for each branch into table*/
DECLARE BranchPointer CURSOR FOR
SELECT b.id, PrefixLength, SequenceLength, s.MinimumSequenceDate
FROM Branch b
INNER JOIN Practice pr ON pr.id = b.practiceid
INNER JOIN [Sequence] s ON s.id = b.id
WHERE pr.APIKey = #pracID
AND b.prefix = #Prefix
AND b.inactive = 0
OPEN BranchPointer
FETCH NEXT FROM BranchPointer INTO #BranchId, #PrefixLength, #SequenceLength, #startDate
WHILE ##FETCH_STATUS = 0
BEGIN
/*get the earliest and latest number in the sequence from the startdate*/
SELECT
#rangestart = MIN(SUBSTRING(v.bookingnumber, 3, LEN(v.bookingnumber))),
#rangeend = MAX(SUBSTRING(v.bookingnumber, 3, LEN(v.bookingnumber)))
FROM Visit v
WHERE v.branchid = #BranchId
AND v.date >= #startDate
AND LEFT(v.bookingnumber, 2) = #Prefix;
SET #RangeNow = #rangestart
WHILE #rangenow < #rangeend
BEGIN
/*Insert full sequence into temporary table*/
INSERT INTO #TempDetails (BranchID, SequenceCheck)
SELECT #BranchId,
#Prefix + REPLICATE('0', #SequenceLength-#PrefixLength-LEN(#rangenow)) + CAST(#RangeNow AS VARCHAR(256));
SET #rangenow =#rangenow+1
END;
FETCH NEXT FROM BranchPointer INTO #BranchId, #PrefixLength, #SequenceLength, #startDate
END
CLOSE BranchPointer
DEALLOCATE BranchPointer
/*delete existing sequence numbers from table*/
DELETE FROM #TempDetails
FROM #TempDetails t
INNER JOIN Visit v ON t.BranchID = v.branchid
WHERE t.SequenceCheck = v.BookingNumber
/*Insert the status and link for error messages*/
UPDATE #tempDetails
SET RisStatus = (SELECT Status
FROM RISErrors r
INNER JOIN Practice pr ON pr.id = r.PracticeId
WHERE pr.APIKey = #pracId
AND VisitNumber = SequenceCheck
AND r.id = (SELECT MAX(r1.id)
FROM RISErrors r1
INNER JOIN Practice pr1 ON pr1.id = r1.PracticeId
WHERE pr1.APIKey = #pracId
AND VisitNumber = SequenceCheck)),
RisLink = 'http://billing.cryanic.co.za/Clinton/RISErrors?searchquery=' + SequenceCheck
/*return missing numbers into sequence control callong procedure*/
SELECT DISTINCT SequenceCheck, RisStatus, Rislink
FROM #TempDetails
END

Executing stored procedure not working but individual statements working in stored procedure

I have the following stored procedure which I am trying to execute.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Create]
(
#OriginatingTransactionID VARCHAR(50),
#AssociatedOriginatingTransactionID VARCHAR(50),
#LineOfBusiness VARCHAR(50),
#RiskState VARCHAR(50),
#OccupationCode VARCHAR(50),
#SourceSystem VARCHAR(50),
#DocumentCategory VARCHAR(50),
#DocumentType VARCHAR(50),
#TransactionFlow VARCHAR(50),
#BundleName VARCHAR(50),
#DocumentID VARCHAR(50),
#DocumentName VARCHAR(50),
#PolicyOrClaimNumber VARCHAR(50),
#EffectiveOrCreationDate DATETIME,
#SignatureDetect BIT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FinalDate DATETIME, #RuleID VARCHAR(50),
#RuleName VARCHAR(50), #CurrentActionID INT,
#BundleTransactionID INT
IF (#SignatureDetect = 'true')
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
UPDATE ecm.bundle_checklist_txn
SET Bundle_Status_Code = 'COMP'
FROM ecm.bundle_checklist_txn bundlechecklist
INNER JOIN (SELECT DISTINCT Bundle_TXN_ID,Document_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE Doc_Status_Code='COMP') COMP
ON COMP.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
AND COMP.Bundle_TXN_ID NOT IN (
SELECT Bundle_TXN_ID FROM ecm.Document_Checklist_TXN documentchecklist
WHERE documentchecklist.Bundle_TXN_ID=COMP.Bundle_TXN_ID AND documentchecklist.Doc_Status_Code<>'COMP')
AND COMP.Document_ID=#DocumentID
WHERE bundlechecklist.Bundle_TXN_ID= #OriginatingTransactionID
AND bundlechecklist.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
UPDATE associatedtransaction
SET Assoc_Orig_Status_Code='COMP'
FROM [ECM].[Assoc_Orig_Tran_TXN] associatedtransaction
INNER JOIN (SELECT DISTINCT Assoc_Orig_Tran_ID from [ECM].[Bundle_Checklist_TXN] bundlechecklist
WHERE bundlechecklist.[Bundle_Status_Code]='COMP')COMP
ON COMP.Assoc_Orig_Tran_ID=associatedtransaction.Assoc_Orig_Tran_ID
WHERE COMP.Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID
END
END
END
ELSE
BEGIN
IF (#OriginatingTransactionID = #AssociatedOriginatingTransactionID)
BEGIN
SELECT #FinalDate =DATEADD(DAY,Number_Of_Days_Till_Next_Action,#EffectiveOrCreationDate),#RuleID= rule1.Action_Rule_ID,#RuleName=rule1.Action_Rule_Name,#currentActionID=rule1.Current_Action_ID FROM ecm.Action_Rule rule1
INNER JOIN ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = #BundleName
AND rulegroup.Line_of_Business_Code=#LineOfBusiness
AND rulegroup.State_Alpha_Code=#RiskState
AND documentcategory.Doc_Categ_Name=#DocumentCategory
AND rulegroup.Exec_Acct_Grp_ID=#OccupationCode
AND rule1.Transaction_Flow=#TransactionFlow
AND sourcesystem.Source_System_Name = #SourceSystem
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name =#DocumentType
IF NOT EXISTS (SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID=#AssociatedOriginatingTransactionID)
BEGIN
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)
BEGIN
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#BundleName,'PEND',#AssociatedOriginatingTransactionID,#OriginatingTransactionID,#DocumentCategory,#FinalDate,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
IF NOT EXISTS (SELECT t.Doc_Checklist_TXN_ID FROM (SELECT bundlechecklist.Bundle_TXN_ID, documentchecklist.Doc_Checklist_TXN_ID, documentchecklist.Doc_Type_Name FROM ecm.bundle_checklist_txn bundlechecklist
LEFT OUTER JOIN [ECM].[Document_Checklist_TXN] documentchecklist ON documentchecklist.Bundle_TXN_ID = bundlechecklist.Bundle_TXN_ID
WHERE bundlechecklist.originating_tran_id = #OriginatingTransactionID AND bundle_name = #BundleName)t WHERE t.Doc_Checklist_TXN_ID is not null )
BEGIN
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, #RuleID, #RuleName, #DocumentType, #DocumentName, #DocumentID, 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
END
END
END
END
In my code, if I execute with values, its not working and and insert fails
with the following error :
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 95
Cannot insert the value NULL into column 'Orig_Tran_Action_Rule_id',
table 'EIC_ECM_Checklist.ECM.Assoc_Orig_Tran_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 104
Cannot insert the value NULL into column 'Bundle_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Bundle_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
Msg 515, Level 16, State 2, Procedure usp_CreateChecklist, Line 117
Cannot insert the value NULL into column 'Document_Action_Rule_ID',
table 'EIC_ECM_Checklist.ECM.Document_Checklist_TXN'; column does not
allow nulls. INSERT fails. The statement has been terminated.
But if I execute individually each line and its working and all values getting stored in the table. All insert statement works. Tried debugging with individual statement. Like below :
SELECT
DATEADD(DAY, Number_Of_Days_Till_Next_Action, '2015-10-18T00:00:00'),
rule1.Action_Rule_ID, rule1.Action_Rule_Name,
rule1.Current_Action_ID
FROM
ecm.Action_Rule rule1
INNER JOIN
ecm.Action_Rule_Group rulegroup ON rulegroup.Action_Rule_Group_ID = rule1.Action_Rule_Group_ID
INNER JOIN
ref.Line_of_Business lob ON lob.Line_of_Business_Code = rulegroup.Line_of_Business_Code
INNER JOIN
ref.State state ON state.State_Alpha_Code=rulegroup.State_Alpha_Code
INNER JOIN
ref.Source_System sourcesystem ON sourcesystem.Source_System_ID = rulegroup.Source_System_ID
INNER JOIN
ecm.[Document Catgeory] documentcategory ON documentcategory.Doc_Categ_ID = rulegroup.Doc_Categ_ID
INNER JOIN ecm.[Document Type] documenttype ON documenttype.Doc_Type_ID=rule1.Doc_Type_ID
INNER JOIN ecm.Exec_Acct_Group occupationgroup ON occupationgroup.Exec_Acct_Grp_ID = rulegroup.Exec_Acct_Grp_ID
INNER JOIN [ECM].[Bundle] bundle ON bundle.Bundle_ID = rule1.Bundle_ID
WHERE
bundle.Bundle_Name = 'Auto'
AND rulegroup.Line_of_Business_Code='A'
AND rulegroup.State_Alpha_Code='FL'
AND documentcategory.Doc_Categ_Name=' review'
AND rulegroup.Exec_Acct_Grp_ID=2
AND rule1.Transaction_Flow='Outgoing doc'
AND sourcesystem.Source_System_Name = 'V4 Policy'
AND rulegroup.Doc_Categ_ID=documentcategory.Doc_Categ_ID
AND documenttype.Doc_Type_Name ='Application'
SELECT Assoc_Orig_Tran_ID FROM [ECM].[Assoc_Orig_Tran_TXN] WHERE Assoc_Orig_Tran_ID='BPA201607131452113541050525A1REN'
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, ASsoc_Orig_Tran_ID, ASsoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','BPA201607131452113541050525A1REN', 'PEND','2015-10-18T00:00:00' , '2015-11-07 00:00:00.000',NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
SELECT originating_tran_id FROM ecm.bundle_checklist_txn WHERE originating_tran_id = 'BPA201607131452113541050525A1REN' AND bundle_name = 'Auto'
INSERT INTO [ECM].[Bundle_Checklist_TXN]
( Bundle_Action_Rule_ID,Bundle_Name,Bundle_Status_Code,ASsoc_Orig_Tran_ID,Originating_Tran_ID,Doc_Categ_Name, Next_Action_Dt,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
('157','Auto','PEND','BPA201607131452113541050525A1REN','BPA201607131452113545050525A1AMD','Underwriting review','2015-11-07 00:00:00.000',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
declare #BundleTransactionID int
SELECT #BundleTransactionID=bundlechecklist.bundle_txn_id FROM [ECM].[Bundle_Checklist_TXN] bundlechecklist
INSERT INTO [ECM].[Document_Checklist_TXN]
(bundle_txn_id, document_action_rule_id, action_rule_name, doc_type_name, cp_document_name, document_id, doc_status_code,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#BundleTransactionID, '157', 'FL Application', 'Application', 'CPLProp_Acknowledgment_FAQs', '321Z01W_007624ZRM00002G', 'PEND',GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Any idea where it fails?
First Error says that you are trying to insert null value to Orig_Tran_Action_Rule_id but this field is NOT NULL so u cannot insert the data.
INSERT INTO [ECM].[ASsoc_Orig_Tran_TXN]
(Orig_Tran_Action_Rule_id, Assoc_Orig_Tran_ID, Assoc_Orig_Status_Code, First_Rule_Date, Final_Actionable_Date, Folder_ID,CREATED_DTM,CREATE_PROCESSNAME,UPDATE_DTM,UPDATE_PROCESSNAME)
VALUES
(#RuleID,#AssociatedOriginatingTransactionID, 'PEND', #EffectiveOrCreationDate, #FinalDate,NULL,GETDATE(),CURRENT_USER,GETDATE(),CURRENT_USER)
Please check #RuleID.
And for other two also the same issue.
And you are right, when you insert individual at that time you provide values('157') instead of Variables(#RuleID).
So it works fine.

How to solve this variable pass into batch_date?

I want to pass in #batch date into batch_date...But it shows error...The error is
Column 'dbo.tnx_tid_InvCheck_Details.Batch_Date' is invalid in the
select list because it is not contained in either an aggregate
function or the GROUP BY clause.
The InvCheck_Details table has batch_date for each and every part_no. I want to group the part_no so that I can count(tid) and sum(tid_bal) by part_no. What should i do in order to run this script? TQ...
DECLARE #batch_date datetime
SET #batch_date = '2012-10-13 00:00:00.000'
CREATE TABLE #inv_check
(batch_date datetime,part_no varchar(25),Number_of_tid int,Updated_DT int, Tot_Tid_Bal int)
INSERT INTO #inv_check
SELECT batch_date,part_no,COUNT(tid)as Number_of_tid,0,sum(Tid_Bal)
FROM dbo.tnx_tid_InvCheck_Details
where batch_date = #batch_date
Group by part_no
order by part_no
UPDATE #inv_check
SET Updated_DT = isnull(d.Updated_DT,0)
--select i.part_no,i.Number_of_tid, isnull(d.Updated_DT,0)
FROM #inv_check i
LEFT OUTER JOIN
(SELECT part_no, COUNT(LastUpdate_DT)as Updated_DT,
sum(tid_bal) as Tid_bal_sum
FROM dbo.tnx_tid_InvCheck_Details
Where NOT LastUpdate_DT IS NULL
Group by part_no) d on i.part_no=d.part_no
DECLARE #sql int
DECLARE #sql1 int
SELECT #sql1 = count(part_no)
FROM #inv_check
SELECT #sql = count(part_no)
FROM #inv_check
WHERE number_of_tid= Updated_DT
SELECT #sql AS Parts_Counted,#sql1 AS Full_Parts
Drop table #inv_check
Try this
INSERT INTO #inv_check
Select y.batch_date,x.*
From dbo.tnx_tid_InvCheck_Details y
Join(
SELECT part_no,COUNT(tid)as Number_of_tid,0 AS Updated_DT,sum(Tid_Bal) As Tot_Tid_Bal
FROM dbo.tnx_tid_InvCheck_Details
where batch_date = #batch_date
Group by part_no
)x
On x.part_no = y.part_no
order by x.part_no

Resources