In the below stored procedure, I'm getting the error mentioned in some cases, what am I doing wrong here?
Error:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1
Stored procedure:
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[prcInsDataFeesForVersion]
(#ContractId INT,
#UserId INT,
#VersionNo INT,
#SelectAll BIT,
#SubProductList NVARCHAR(MAX),
#ConvRateFlag BIT)
AS
BEGIN
SET NOCOUNT ON
DECLARE #RetVal INT,
#ErrMsg VARCHAR(255),
#FunctionId INT = 1234,
#AppId VARCHAR(20) = 'ID1021',
#FeesOverrideFlg BIT = 1,
#ContractProdFeeVerSummId INT
CREATE TABLE #tblMasterData
(
ProdCd INT,
ProdName NVARCHAR(255),
SubProdCd INT,
SubProdName NVARCHAR(255),
ProdTypeCd INT,
ProdDeliveryTypCd INT,
ProdStatusCd INT,
ProdStatusDt DATETIME,
CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFiltered
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, ContractProdFeeId INT
, FeeTypCd INT
, RowMatrixParameterCd INT
, CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFilteredInsert
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, FeeTypCd INT
, FeeDeterminantCd INT
, RowMatrixParameterCd INT
, ProdFeeCurrCd INT
, RowParameterValueCd INT
, ColumnParameterValueCd INT
, ProdFeePct REAL
, RangeFromDayCnt INT
, RangeToDayCnt INT
, ProdFeeLevelMinAmt DECIMAL
, ProdFeeLevelMaxAmt DECIMAL
, ProdFeeAmt DECIMAL
, ContractProdFeeId INT
, CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFilteredUpdate
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, FeeTypCd INT
, FeeDeterminantCd INT
, RowMatrixParameterCd INT
, ProdFeeCurrCd INT
, RowParameterValueCd INT
, ColumnParameterValueCd INT
, ProdFeePct REAL
, RangeFromDayCnt INT
, RangeToDayCnt INT
, ProdFeeLevelMinAmt DECIMAL
, ProdFeeLevelMaxAmt DECIMAL
, ProdFeeAmt DECIMAL
, ContractProdFeeId INT
, CreatedDate DATETIME
)
CREATE TABLE #tblSelContractSubProds
(
ContractSubProdId INT
)
BEGIN TRY
BEGIN TRANSACTION
IF(#SelectAll=0 AND #SubProductList IS NOT NULL)
BEGIN
INSERT INTO #tblSelContractSubProds
SELECT intValue FROM dbo.udfSplit(#SubProductList,',',1)
END
INSERT INTO #tblMasterData(
ProdCd
, ProdName
, SubProdCd
, SubProdName
, ProdTypeCd
, ProdDeliveryTypCd
, ProdStatusCd
, ProdStatusDt
, CreatedDate
)
SELECT P.ProdCd
, PC.Descr
, S.SubProdCd
, SC.Descr
, P.ProdTypeCd
, P.ProdDeliveryTypCd
, P.ProdStatusCd
, P.ProdStatusDt
, GETDATE()
FROM tblProduct(NOLOCK) as P
INNER JOIN tblCode(NOLOCK) as PC ON P.ProdCd=PC.Cd and PC.Typ=1053
INNER JOIN tblSubProdDetail(NOLOCK) as S ON P.ProdCd=S.ProdCd
INNER JOIN tblCode(NOLOCK) as SC ON S.SubProdCd=SC.Cd and SC.Typ=1053
WHERE P.ProdDeliveryTypCd=3 and P.ProdStatusCd=1
IF(#SelectAll=1)
BEGIN
INSERT INTO #tblContractInterCulturalDataFiltered(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, ContractProdFeeId
, FeeTypCd
, RowMatrixParameterCd
, CreatedDate
)
SELECT DISTINCT CP.ContractId,
CP.ContractProdId,
CP.ProdCd,
CPC.Descr,
CSP.ContractSubProdID,
CSP.SubProdCd,
CSPC.Descr,
CP.ContractProdStatusCd,
CP.ContractProdStatusDt,
CSP.ContractSubProdStatusCd,
CSP.ContractSubProdStatusDt,
CPF.ContractProdFeeId,
CPF.FeeTypCd,
CPF.RowMatrixParameterCd,
Getdate()
FROM #tblMasterData(NOLOCK) MD
INNER JOIN tblContractProd(NOLOCK) CP ON MD.ProdCd=CP.ProdCd
INNER JOIN tblContractSubProd(NOLOCK) CSP ON CP.ContractProdId=CSP.ContractProdId
INNER JOIN tblCode(NOLOCK) CPC ON CP.ProdCd=CPC.Cd and CPC.Typ=1053
INNER JOIN tblCode(NOLOCK) CSPC ON CSP.SubProdCd=CSPC.Cd and CSPC.Typ=1053
INNER JOIN tblContractProdFee(NOLOCK) CPF ON CP.ContractProdID=CPF.ContractProdId AND CSP.ContractSubProdID=CPF.ContractSubProdId
WHERE ContractId=#ContractId AND CP.ContractProdStatusCd=1 AND CSP.ContractSubProdStatusCd=1
AND CPF.ContractProdFeeTypStatusCd=1 AND CP.StandardProdIndCd=1 AND CSP.StdSubProdIndCd=1
END
ELSE
BEGIN
IF(#SubProductList IS NOT NULL)
BEGIN
INSERT INTO #tblContractInterCulturalDataFiltered(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, ContractProdFeeId
, FeeTypCd
, RowMatrixParameterCd
, CreatedDate
)
SELECT DISTINCT CP.ContractId,
CP.ContractProdId,
CP.ProdCd,
CPC.Descr,
CSP.ContractSubProdID,
CSP.SubProdCd,
CSPC.Descr,
CP.ContractProdStatusCd,
CP.ContractProdStatusDt,
CSP.ContractSubProdStatusCd,
CSP.ContractSubProdStatusDt,
CPF.ContractProdFeeId,
CPF.FeeTypCd,
CPF.RowMatrixParameterCd,
Getdate()
FROM #tblMasterData(NOLOCK) MD
INNER JOIN tblContractProd(NOLOCK) CP ON MD.ProdCd=CP.ProdCd
INNER JOIN tblContractSubProd(NOLOCK) CSP ON CP.ContractProdId=CSP.ContractProdId
INNER JOIN tblCode(NOLOCK) CPC ON CP.ProdCd=CPC.Cd and CPC.Typ=1053
INNER JOIN tblCode(NOLOCK) CSPC ON CSP.SubProdCd=CSPC.Cd and CSPC.Typ=1053
INNER JOIN tblContractProdFee(NOLOCK) CPF ON CP.ContractProdID=CPF.ContractProdId AND CSP.ContractSubProdID=CPF.ContractSubProdId
INNER JOIN #tblSelContractSubProds(NOLOCK) SCSP ON CSP.ContractSubProdId=SCSP.ContractSubProdId
WHERE ContractId=#ContractId AND CP.ContractProdStatusCd=1 AND CSP.ContractSubProdStatusCd=1
AND CPF.ContractProdFeeTypStatusCd=1 AND CP.StandardProdIndCd=1 AND CSP.StdSubProdIndCd=1
END
END
INSERT INTO #tblContractInterCulturalDataFilteredUpdate(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, FeeTypCd
, FeeDeterminantCd
, RowMatrixParameterCd
, ProdFeeCurrCd
, RowParameterValueCd
, ColumnParameterValueCd
, ProdFeePct
, RangeFromDayCnt
, RangeToDayCnt
, ProdFeeLevelMinAmt
, ProdFeeLevelMaxAmt
, ProdFeeAmt
, ContractProdFeeId
, CreatedDate
)
SELECT DISTINCT CICF.ContractId,
CICF.ContractProdId,
CICF.ProdCd,
CICF.ProdName,
CICF.ContractSubProdID,
CICF.SubProdCd,
CICF.SubProdName,
CICF.ContractProdStatusCd,
CICF.ContractProdStatusDt,
CICF.ContractSubProdStatusCd,
CICF.ContractSubProdStatusDt,
CPFM.FeeTypCd,
CPFM.FeeDeterminantCd,
CPFM.RowMatrixParameterCd,
CPFM.ProdFeeCurrCd,
CPFM.RowParameterValueCd,
CPFM.ColumnParameterValueCd,
CPFM.ProdFeePct,
CPFM.RangeFromDayCnt,
CPFM.RangeToDayCnt,
CPFM.ProdFeeLevelMinAmt,
CPFM.ProdFeeLevelMaxAmt,
CPFM.ProdFeeAmt,
CICF.ContractProdFeeId,
Getdate()
FROM #tblContractInterCulturalDataFiltered(NOLOCK) CICF
INNER JOIN tblContractProdFeeMatrix(NOLOCK) CPFM ON CICF.ProdCd=CPFM.FeeMatrixProdCd AND CICF.SubProdCd=CPFM.FeeMatrixSubProdCd AND CICF.FeeTypCd=CPFM.FeeTypCd
INNER JOIN tblContractProdFeeMatrixVersion(NOLOCK) CPFMV ON CPFM.ContractProdFeeMatrixVersionId=CPFMV.ContractProdFeeMatrixVersionId
INNER JOIN tblContractProdFee(NOLOCK) CP ON CICF.ContractProdID=CP.ContractProdId AND CICF.ContractSubProdID=CP.ContractSubProdId AND CICF.ContractProdFeeId=CP.ContractProdFeeId
AND CPFM.FeeDeterminantCd=CP.FeeDeterminantCd AND CPFM.RowMatrixParameterCd =CP.RowMatrixParameterCd
WHERE CICF.ContractId=#ContractId AND CPFMV.ProdFeeMatrixVerNo=#VersionNo AND CICF.ContractProdStatusCd=1 AND CICF.ContractSubProdStatusCd=1 AND CP.ContractProdFeeTypStatusCd=1
AND CPFM.RowMatrixParameterCd IN(6,4)
AND EXISTS(SELECT PFM.ContractProdFeeId from tblProdFeeMatrix(NOLOCK)PFM WHERE CICF.ContractProdFeeId=PFM.ContractProdFeeId)
IF EXISTS(Select 1 From #tblContractInterCulturalDataFilteredUpdate(NOLOCK))
BEGIN
DELETE PFM
FROM tblProdFeeMatrix(NOLOCK) PFM
INNER JOIN #tblContractInterCulturalDataFilteredUpdate(NOLOCK) TIFU ON TIFU.ContractProdFeeId=PFM.ContractProdFeeId
END
INSERT INTO #tblContractInterCulturalDataFilteredInsert(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, FeeTypCd
, FeeDeterminantCd
, RowMatrixParameterCd
, ProdFeeCurrCd
, RowParameterValueCd
, ColumnParameterValueCd
, ProdFeePct
, RangeFromDayCnt
, RangeToDayCnt
, ProdFeeLevelMinAmt
, ProdFeeLevelMaxAmt
, ProdFeeAmt
, ContractProdFeeId
, CreatedDate
)
SELECT DISTINCT CICF.ContractId,
CICF.ContractProdId,
CICF.ProdCd,
CICF.ProdName,
CICF.ContractSubProdID,
CICF.SubProdCd,
CICF.SubProdName,
CICF.ContractProdStatusCd,
CICF.ContractProdStatusDt,
CICF.ContractSubProdStatusCd,
CICF.ContractSubProdStatusDt,
CPFM.FeeTypCd,
CPFM.FeeDeterminantCd,
CPFM.RowMatrixParameterCd,
CPFM.ProdFeeCurrCd,
CPFM.RowParameterValueCd,
CPFM.ColumnParameterValueCd,
CPFM.ProdFeePct,
CPFM.RangeFromDayCnt,
CPFM.RangeToDayCnt,
CPFM.ProdFeeLevelMinAmt,
CPFM.ProdFeeLevelMaxAmt,
CPFM.ProdFeeAmt,
CICF.ContractProdFeeId,
Getdate()
FROM #tblContractInterCulturalDataFiltered(NOLOCK) CICF
INNER JOIN tblContractProdFeeMatrix(NOLOCK) CPFM ON CICF.ProdCd=CPFM.FeeMatrixProdCd AND CICF.SubProdCd=CPFM.FeeMatrixSubProdCd AND CICF.FeeTypCd=CPFM.FeeTypCd
INNER JOIN tblContractProdFeeMatrixVersion(NOLOCK) CPFMV ON CPFM.ContractProdFeeMatrixVersionId=CPFMV.ContractProdFeeMatrixVersionId
INNER JOIN tblContractProdFee(NOLOCK) CP ON CICF.ContractProdID=CP.ContractProdId AND CICF.ContractSubProdID=CP.ContractSubProdId AND CICF.ContractProdFeeId=CP.ContractProdFeeId
AND CPFM.FeeDeterminantCd=CP.FeeDeterminantCd AND CPFM.RowMatrixParameterCd =CP.RowMatrixParameterCd
WHERE CICF.ContractId=#ContractId AND CPFMV.ProdFeeMatrixVerNo=#VersionNo AND CICF.ContractProdStatusCd=1 AND CICF.ContractSubProdStatusCd=1 AND CP.ContractProdFeeTypStatusCd=1
AND CPFM.RowMatrixParameterCd IN(6,4)
IF EXISTS(Select 1 From #tblContractInterCulturalDataFilteredInsert(NOLOCK))
BEGIN
INSERT INTO [dbo].[tblProdFeeMatrix]
([ContractProdFeeId]
,[ContractBundleFeeId]
,[ContractProdBundleAncilFeeId]
,[RowParameterValueCd]
,[ColumnParameterValueCd]
,[ProdFeeAmt]
,[ProdFeeCurrCd]
,[ProdFeePct]
,[RangeFromDayCnt]
,[RangeToDayCnt]
,[RangeFromPct]
,[RangeToPct]
,[RangeFromAmt]
,[RangeToAmt]
,[ProdFeeLevelMinAmt]
,[ProdFeeLevelMaxAmt]
,[FeeNotApplyIndCd]
,[CreateId]
,[CreateDt]
,[UpdateId]
,[UpdateDt]
,[FunctionId])
SELECT DISTINCT
TIFI.ContractProdFeeID,
0,
0,
TIFI.RowParameterValueCd,
TIFI.ColumnParameterValueCd,
TIFI.ProdFeeAmt,
TIFI.ProdFeeCurrCd,
TIFI.ProdFeePct,
TIFI.RangeFromDayCnt,
TIFI.RangeToDayCnt,
0,
0,
0,
0,
TIFI.ProdFeeLevelMinAmt,
TIFI.ProdFeeLevelMaxAmt,
0,
#UserId,
GETDATE(),
#UserId,
GETDATE(),
#FunctionId
FROM #tblContractInterCulturalDataFilteredInsert(NOLOCK) TIFI
END
IF(#ConvRateFlag=1)
BEGIN
EXEC [ASSET_DB].[dbo].[prcCalculateRates] #UserId,#ContractId,#SelectAll,#SubProductList,#FeesOverrideFlg
END
COMMIT TRANSACTION
SELECT #RetVal=0
GOTO CLEARTEMPTABLES
GOTO DONE
END TRY
BEGIN CATCH
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 200
GOTO CLEARTEMPTABLES
GOTO ERROR
END CATCH
ERROR:
ROLLBACK TRANSACTION
RAISERROR(#ErrMsg,16,1 )
CLEARTEMPTABLES:
BEGIN TRY
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblMasterData]') )
BEGIN
TRUNCATE TABLE #tblMasterData
DROP TABLE #tblMasterData
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFiltered]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFiltered
DROP TABLE #tblContractInterCulturalDataFiltered
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFilteredInsert]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFilteredInsert
DROP TABLE #tblContractInterCulturalDataFilteredInsert
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFilteredUpdate]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFilteredUpdate
DROP TABLE #tblContractInterCulturalDataFilteredUpdate
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblSelContractSubProds]') )
BEGIN
TRUNCATE TABLE #tblSelContractSubProds
DROP TABLE #tblSelContractSubProds
END
END TRY
BEGIN CATCH
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 201
GOTO ERROR
END CATCH
DONE:
SET NOCOUNT OFF
Return (#RetVal)
END
The fact that lead to this error is that the BEGIN TRANSACTION executed, but neither COMMIT or ROLLBACK did.
The usual reason a stored procedure with a try-transaction block returns that message is the error: table (or other object) not found. This is NOT caught in the try-catch block.
Check the object names exist on runtime.
Also, make sure to run a ROLLBACK manually on the session that spawned this message, if you still haven't fixed the proc.
Documentation:
The following types of errors are not handled by a CATCH block when
they occur at the same level of execution as the TRY...CATCH
construct:
(........)
Object name resolution errors
As you can see, there are also other errors not caught which may be the problem. Check out the possibilities. Many of these error, including the object name resolution, can be caught if you put the procedure CALL inside a try-catch block.
begin try
exec [dbo].[prcInsDataFeesForVersion] ..............
end try
begin catch
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 201
end catch
This might not sound handy, but at least you can use it to find the error out.
I have a website for an NFL Pool. I'm able to display User Picks and the amount of Wins user has. As of now my CASE WHEN is using integer as win or lost. I would like to change it to be where 1 = 'Won' and 0 = 'Lost' but still count the amount of wins the user has.
Is this possible?
Thanks for any help.
My code:
DECLARE #commondata TABLE (FullName VARCHAR(30), Game_1 VARCHAR(30), Game_2 VARCHAR(30), Game_3 VARCHAR(30), Game_4 VARCHAR(30), Game_5 VARCHAR(30),
GameResults_1 INT, GameResults_2 INT, GameResults_3 INT, GameResults_4 INT, GameResults_5 INT)
INSERT INTO #commondata (FullName, Game_1, Game_2, Game_3, Game_4, Game_5,
GameResults_1, GameResults_2 , GameResults_3, GameResults_4, GameResults_5)
SELECT UserPicks.FullName, UserPicks.Game_1, UserPicks.Game_2, UserPicks.Game_3, UserPicks.Game_4, UserPicks.Game_5,
(CASE WHEN UserPicks.Game_1 = WeeklyResults.GameResults_1 THEN 1 ELSE 0 END) AS GameResult_1,
(CASE WHEN UserPicks.Game_2 = WeeklyResults.GameResults_2 THEN 1 ELSE 0 END) AS GameResult_2,
(CASE WHEN UserPicks.Game_3 = WeeklyResults.GameResults_3 THEN 1 ELSE 0 END) AS GameResult_3,
(CASE WHEN UserPicks.Game_4 = WeeklyResults.GameResults_4 THEN 1 ELSE 0 END) AS GameResult_4,
(CASE WHEN UserPicks.Game_5 = WeeklyResults.GameResults_5 THEN 1 ELSE 0 END) AS GameResult_5
FROM UserPicks
JOIN WeeklyResults ON UserPicks.Week = WeeklyResults.Week
WHERE WeeklyResults.Week = 'Week1'
-- Unpivot the table.
(SELECT FullName, Game_1, Game_2, Game_3, Game_4, Game_5, SUM(Points) As Total
FROM
(SELECT *
FROM #commondata) pvt
UNPIVOT
(Points FOR Game IN
(GameResults_1, GameResults_2, GameResults_3, GameResults_4, GameResults_5)
)AS Total
GROUP BY FullName, Game_1, Game_2, Game_3, Game_4, Game_5)
Try this, I took the liberty to reformat, remove redundant lines and use table acronyms to make it easier to read/understand:
DECLARE #commondata TABLE (FullName VARCHAR(30)
, Game_1 VARCHAR(30)
, Game_2 VARCHAR(30)
, Game_3 VARCHAR(30
, Game_4 VARCHAR(30)
, Game_5 VARCHAR(30)
, GameResults_1 VARCHAR(4)
, GameResults_2 VARCHAR(4)
, GameResults_3 VARCHAR(4)
, GameResults_4 VARCHAR(4)
, GameResults_5 VARCHAR(4));
INSERT INTO #commondata
SELECT UP.FullName
, UP.Game_1
, UP.Game_2
, UP.Game_3
, UP.Game_4
, UP.Game_5
, IIF(UP.Game_1 = WR.GameResults_1, 'Won', 'Lost') AS GameResult_1
, IIF(UP.Game_2 = WR.GameResults_2, 'Won', 'Lost') AS GameResult_2
, IIF(UP.Game_3 = WR.GameResults_3, 'Won', 'Lost') AS GameResult_3
, IIF(UP.Game_4 = WR.GameResults_4, 'Won', 'Lost') AS GameResult_4
, IIF(UP.Game_5 = WR.GameResults_5, 'Won', 'Lost') AS GameResult_5
FROM UserPicks UP
JOIN WeeklyResults WR ON UP.Week = WR.Week
WHERE WR.Week = 'Week1';
-- Unpivot the table.
SELECT FullName
, Game_1
, Game_2
, Game_3
, Game_4
, Game_5
, SUM(IIF(Result='Won', 1, 0)) As Total
FROM #commondata
UNPIVOT (
Result FOR Game IN (GameResults_1
, GameResults_2
, GameResults_3
, GameResults_4
, GameResults_5)
) AS Total
GROUP BY FullName
, Game_1
, Game_2
, Game_3
, Game_4
, Game_5;
I have the below sql. I am wanting my results to be grouped if the boolean is checked 0, but not grouped if the boolean is checked 1. Is the code below a good way of doing this? I feel like it should work but it is throwing the error "InvoicePeriodID is invalid in the select list because it is not contained in an aggraagte function or group by" Any advice?
----insert invoices for rebates grouped by date, address, contract, rebate note, and order type
declare #invoices table(InvoicePeriodID int, InvoiceStartDate datetime, InvoiceEndDate datetime, JDEAddressNo float, ContractID int, RebateNoteID int, JDEOrderType char(2), RebateInvoiceID int)
insert #invoices (InvoicePeriodID , InvoiceStartDate , InvoiceEndDate , JDEAddressNo , ContractID , RebateNoteID, JDEOrderType)
select
i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from
#inv i
group by
case i.InvoiceSeparately
when 1 then null
when 0 then i.InvoicePeriodID
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.InvoiceStartDate
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.InvoiceEndDate
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.JDEAddressNo
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.ContractID
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.RebateNoteId
end
, case i.InvoiceSeparately
when 1 then null
when 0 then i.JDEOrderType
end
I think it is more readable and easier to do what you want this way
select
i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from
#inv i
WHERE i.InvoiceSeparately = 0
group BY i.InvoicePeriodID
,i.InvoiceStartDate
,i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
,i.RebateNoteId
, i.JDEOrderType
UNION ALL
select
i.InvoicePeriodID
, i.InvoiceStartDate
, i.InvoiceEndDate
, i.JDEAddressNo
, i.ContractID
, i.RebateNoteID
, i.JDEOrderType
from
#inv i
WHERE i.InvoiceSeparately = 1
I need to filter cte data by procedure parameters- in fact if #agentid is null gives me all data else filter data by #agentid . I tried many ways , I used case in cte and get erros , I used if in ( if #status after cte ) and I get errors to , I used if in cte and get errors
This procedure is for pagination and filter data and in works fine .
USE [HN_PRODUCTION]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[grid_data_pagination]
#status int = null
, #offset int = 0
, #limit int = 2
, #agentid int = null
, #start_date date = null
, #end_date date = null
AS
BEGIN
IF #status is null
BEGIN
with cte as
(
Select FilePath , ReceptionLocalTime , AgentID , FileDuration , PhoneNumber , Indice , Status , ROW_NUMBER() over ( order by ID ) as RowNumber
from dbo.V1_594
)
select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber as تلفن , Indice as اندیس , Status as وضعیت
from cte
where cte.RowNumber > #limit * #offset and cte.RowNumber <= #limit * ( #offset + 1 )
END
ELSE
BEGIN
with cte as
(
Select FilePath , ReceptionLocalTime , FileDuration , PhoneNumber , Indice , Status , ROW_NUMBER() over ( order by ID ) as RowNumber
from dbo.V1_594
WHERE Status = #status
)
select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber as تلفن , Indice as اندیس
from cte
where cte.RowNumber > #limit * #offset and cte.RowNumber <= #limit * ( #offset + 1 ) ;
END
END
I would be helpful to include the errors you get, but perhaps this will help.
If I understand the problem correctly, you want to filter out the values of the CTE?
You don't need the IF statement for status. You can do that all in the where clause
ALTER PROCEDURE [dbo].[grid_data_pagination]
#status int = null
, #offset int = 0
, #limit int = 2
, #agentid int = null
, #start_date date = null
, #end_date date = null
AS
BEGIN
with cte as
(
Select FilePath, ReceptionLocalTime, AgentID, FileDuration, PhoneNumber, Indice, Status, ROW_NUMBER() over ( order by ID ) as RowNumber
from dbo.V1_594
WHERE (#agentid IS NULL OR AgentId = #agentid)
AND (#status IS NULL OR Status = #status)
)
select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber as تلفن , Indice as اندیس
from cte
where cte.RowNumber > #limit * #offset and cte.RowNumber <= #limit * ( #offset + 1 ) ;
END
Hope that helps
First and foremost, the SQL is handled dynamically by the server, therefore some items in my WHERE clause may look odd to you, please disregard these as they are not an issue.
Per my clients request, they needed to UNION in two other conditions to my update report (/Patients without a Patient Visit/) and (/Patients without a Appointment/). I need help adding in the patients of these two subsets into my final update query. In its present state, it's only adding in the #Temp patients and I need to incorporate the additional patients.
Any help is GREATLY appreciated.
My current SQL update -
DECLARE #Inactive INT
DECLARE #Active INT
DECLARE #PatientProfileId INT
SELECT
#Inactive = MedlistsId
FROM
Medlists
WHERE
TableName = 'PatientProfileStatus'
AND Code = 'I'
SELECT
#Active = MedlistsId
FROM
Medlists
WHERE
TableName = 'PatientProfileStatus'
AND Code = 'A'
CREATE TABLE #Temp
(
PatientName VARCHAR(120) ,
PatientProfileId INT ,
RecentId INT ,
Recent DATETIME
)
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
MAX(pv.PatientVisitId) AS RecentId ,
MAX(pv.Visit) AS Recent
FROM
PatientVisit pv
INNER JOIN PatientProfile pp ON pv.PatientProfileId = pp.PatientProfileId
AND pp.PatientStatusMId = #Active
WHERE
pp.PatientProfileId IN ( SELECT
a.OwnerId
FROM
Appointments a
INNER JOIN PatientProfile pp ON a.OwnerId = pp.PatientProfileId
AND a.ApptKind = 1
AND pp.PatientStatusMId = #Active
GROUP BY
a.OwnerId ,
a.ApptKind
HAVING
MAX(a.ApptStart) < '07/30/2005' )
GROUP BY
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) ,
pp.PatientProfileId
HAVING
MAX(pv.Visit) < '07/30/2005'
/*Patients without a Appointment*/
IF 1 = 1
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
NULL AS RecentId ,
NULL AS Recent
FROM
PatientProfile pp
LEFT JOIN ( SELECT * FROM Medlists WHERE TableName = 'PatientProfileStatus' ) ml1 ON pp.PatientStatusMId = ml1.MedlistsId
LEFT JOIN Appointments a ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
LEFT JOIN PatientVisit pv ON a.PatientVisitId = pv.PatientVisitId
WHERE
ml1.Code = 'A'
AND a.ownerid IS NULL
AND --Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
/*Patients without a Patient Visit*/
IF 0 = 1
INSERT INTO #Temp
SELECT
dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
pp.PatientProfileId ,
NULL AS RecentId ,
NULL AS Recent
FROM
PatientProfile pp
LEFT JOIN PatientVisit pv ON pv.PatientProfileid = pp.PatientProfileid
LEFT JOIN ( SELECT * FROM Medlists WHERE TableName = 'PatientProfileStatus' ) ml1 ON pp.PatientStatusMId = ml1.MedlistsId
WHERE
ml1.Code = 'A'
AND pv.patientprofileid IS NULL
AND --Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
DECLARE curPatient CURSOR FORWARD_ONLY READ_ONLY LOCAL
FOR
SELECT
t.PatientProfileId
FROM
#Temp t
JOIN PatientProfile pp ON t.PatientProfileId = pp.PatientProfileId
JOIN PatientVisit pv ON pp.PatientProfileId = pv.PatientProfileId
AND pv.PatientVisitId = t.RecentId
WHERE
--Filter on Age
(
((
'-1' = '-1'
AND '40' = '125'
)
OR ( CAST(( DATEDIFF(DAY , pp.Birthdate , GETDATE()) / 365.25 ) AS INT) BETWEEN ( '-1' ) AND ( '40' ) ))
)
OPEN curPatient
FETCH NEXT FROM curPatient INTO #PatientProfileId
WHILE ##FETCH_STATUS = 0
BEGIN
UPDATE
PatientProfile
SET
PatientStatusMId = #Inactive ,
pstatus = 'I'
FROM
PatientProfile P
INNER JOIN #Temp t ON t.PatientProfileID = P.PatientProfileID
WHERE
p.PatientProfileId = #PatientProfileId
FETCH NEXT FROM curPatient INTO #PatientProfileId
END
CLOSE curPatient
DEALLOCATE curPatient
DROP TABLE #Temp
This will limit to patients WITH an appointment
LEFT JOIN Appointments a
ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
This will limit to patients WITH a Visit
LEFT JOIN PatientVisit pv
ON pv.PatientProfileid = pp.PatientProfileid
Try
LEFT OUTER JOIN Appointments a
ON a.Ownerid = pp.PatientProfileId
AND a.ApptKind = 1
Where a.Ownerid is null
LEFT OUTER JOIN PatientVisit pv
ON pv.PatientProfileid = pp.PatientProfileid
Where pv.PatientProfileid is null