SQL Stored procedure if (#variable = 0) doesn't work - sql

I've created a Stored procedure with some variables and a nested if statement.
When I call the Stored procedure from my program and check the returned dataset for the returned values, my dataset is empty while there should be records in it. After some testing I noticed when the statement if (#PoolID = 0) is tested and #PoolID is 0, it won't go trough the if statement... So whenever I set the variable poolid to 0 in my code I get the results from the else statement...
Anybody who knows what's going wrong?
Thx
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Pool_select]
#PartnerCode nvarchar(8),
#GebrID int,
#PoolID int,
#Bevoegdheid int
AS
IF (#PoolID = 0)
BEGIN
IF (#Bevoegdheid < 3)
BEGIN
SELECT
p.*,
pr.poolrecht
FROM racpPool p, racpPoolrecht pr
WHERE
p.poolid = pr.poolid and
p.PartnerCode = #PartnerCode and
pr.poolrecht > 0 and
p.actief = 1 and
pr.GebrID = #GebrID
END
ELSE
BEGIN
SELECT *
FROM racpPool p
WHERE standaardpool = 1
and partnercode = #PartnerCode
END
END
ELSE
BEGIN
IF (#Bevoegdheid < 3)
BEGIN
SELECT
p.*,
pr.poolrecht
FROM racpPool p, racpPoolrecht pr
WHERE
p.poolid = pr.poolid and
p.PartnerCode = #PartnerCode and
pr.poolrecht > 0 and
p.actief = 1 and
pr.GebrID = #GebrID and
p.PoolID = #PoolID
END
ELSE IF (#Bevoegdheid >= 3)
BEGIN
SELECT *
FROM racpPool p
WHERE PoolID = #PoolID
END
END

You could rewrite it as one single select of 4-part UNION ALL.
I also notice that your conditions are not comprehensive, not sure if that is intentional.
In the 2nd branch of #PoolID = 0 , the tests are specifically #Bevoegdheid < 3 and #Bevoegdheid >= 3 (instead of ELSE ) which will do nothing if #Bevoegdheid IS NULL
The optimizer will only run the branch that fits the criteria marked with <<<
ALTER PROCEDURE [dbo].[Pool_select]
#PartnerCode nvarchar(8),
#GebrID int,
#PoolID int,
#Bevoegdheid int
-- WITH RECOMPILE -- << may need this
AS
SELECT
p.*,
pr.poolrecht
FROM racpPool p, racpPoolrecht pr
WHERE
p.poolid = pr.poolid and
p.PartnerCode = #PartnerCode and
pr.poolrecht > 0 and
p.actief = 1 and
pr.GebrID = #GebrID
AND #PoolID = 0 and #Bevoegdheid < 3 --- <<<
UNION ALL
SELECT *, NULL
FROM racpPool p
WHERE standaardpool = 1
and partnercode = #PartnerCode
AND #PoolID = 0 and IsNull(#Bevoegdheid,4) >= 3 --- <<<
UNION ALL
SELECT
p.*,
pr.poolrecht
FROM racpPool p, racpPoolrecht pr
WHERE
p.poolid = pr.poolid and
p.PartnerCode = #PartnerCode and
pr.poolrecht > 0 and
p.actief = 1 and
pr.GebrID = #GebrID and
p.PoolID = #PoolID
AND Isnull(#PoolID,-1) <> 0 AND #Bevoegdheid < 3 --- <<<
UNION ALL
SELECT *, NULL
FROM racpPool p
WHERE PoolID = #PoolID
AND Isnull(#PoolID,-1) <> 0 AND #Bevoegdheid >= 3 --- <<<

Related

"IN Clause" causing "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."

I am having difficulty getting past this error message.
This query works:
declare
#warehouseID int =-1,
#type int=2, --0 = all; 1 = serial;2 = nonserial
#LocationID int =0
SELECT Sum(Quantity) AS Quantity,
WarehouseName,
WarehouseID,
sil.Location,
max(si.RecordID) as test,
min(si.RecordID) as test2,
-- (SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
-- )
-- as test4,
(select max(Case When Serial_Number>'' Then COALESCE(si.SoldDate,'') else sih.TransactionDate end ) AS SoldDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
Join SS_Inventory_History sih on InventoryID =sih.RecordID and sih.configStage = 7
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND ((si.Quantity=0 and Serial_Number>'') or (Serial_Number=''))
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
) AS SoldDate,
max(si.ReceivedDate) AS ReceivedDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND Quantity>0
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
GROUP BY WarehouseName,
WarehouseID,
Location,
Part_Number,
Dist_Part_Num
but when i add/uncomment
(SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
)
as test4,
so that it looks like
declare
#warehouseID int =-1,
#type int=2, --0 = all; 1 = serial;2 = nonserial
#LocationID int =0
SELECT Sum(Quantity) AS Quantity,
WarehouseName,
WarehouseID,
sil.Location,
--delete me?
max(si.RecordID) as test,
min(si.RecordID) as test2,
(SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
)
as test4,
(select max(Case When Serial_Number>'' Then COALESCE(si.SoldDate,'') else sih.TransactionDate end ) AS SoldDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
Join SS_Inventory_History sih on InventoryID =sih.RecordID and sih.configStage = 7
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND ((si.Quantity=0 and Serial_Number>'') or (Serial_Number=''))
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
) AS SoldDate,
max(si.ReceivedDate) AS ReceivedDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND Quantity>0
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
GROUP BY WarehouseName,
WarehouseID,
Location,
Part_Number,
Dist_Part_Num
I get this error message:
Msg 8120, Level 16, State 1, Line 15
Column 'SS_Inventory.RecordID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Does anyone have any idea what I am doing wrong?

Update column by calling function is very slow - how to improve? SQL Server

I need to update some column by calling a function. It takes a too long time.
How can I improve it? What could be the reason it takes so long?
I realized that scalar-function takes more time than a table-function, but I have no idea how to convert this to a table function, is there perhaps another way to do this?
The code that updates:
UPDATE EDBNationalInsuranceMortgageLoad_tmp
SET IsDead = dbo.GetIsDead(IdentityNumber1, #FileId) -- the function
The code of the function:
ALTER FUNCTION [dbo].[GetIsDead]
(#IdentityNumber1 NVARCHAR(9),
#FileId INT)
RETURNS int
AS
BEGIN
DECLARE #mateIdentityNumber NVARCHAR(9);
DECLARE #fullRow1_tmp TABLE
(
IdentityNumber NVARCHAR(9),
MateIdentityNumber NVARCHAR(9),
DeathDate NVARCHAR(8)
);
DECLARE #fullRow2_tmp TABLE
IdentityNumber NVARCHAR(9),
MateIdentityNumber NVARCHAR(9),
DeathDate NVARCHAR(8)
);
DECLARE #countRows2 INT
DECLARE #isDead1 INT = 0
DECLARE #isDead2 INT = 0
SET #mateIdentityNumber = (SELECT TOP 1 MateIdentityNumber
FROM MortgageReturnParticipationBase
WHERE IdentityNumber = #IdentityNumber1
AND MortgageReturnParticipationStatusId = 1)
INSERT INTO #fullRow1_tmp
SELECT TOP 1 IdentityNumber1, IdentityNumber2, DeathDate
FROM EDBNationalInsuranceMortgageLoad_tmp
WHERE IdentityNumber1 = #IdentityNumber1
AND IsRowError = 0
AND FileId = #FileId
SET #isDead1 = (SELECT 1
FROM #fullRow1_tmp
WHERE DeathDate IS NOT NULL)
IF #mateIdentityNumber = 0
BEGIN
IF (#isDead1 = 1)
RETURN 0;
ELSE
RETURN 1;
END
ELSE
BEGIN
INSERT INTO #fullRow2_tmp
SELECT TOP 1 IdentityNumber1, IdentityNumber2, DeathDate
FROM EDBNationalInsuranceMortgageLoad_tmp
WHERE IdentityNumber1 = #mateIdentityNumber
AND IsRowError = 0
AND FileId = #FileId
SET #countRows2 = (SELECT COUNT(*) FROM #fullRow2_tmp)
IF #countRows2 = 0
RETURN 2;
SET #isDead2 = (SELECT 1 FROM #fullRow2_tmp WHERE DeathDate IS NOT NULL)
IF (#isDead1 IS NULL OR #isDead2 IS NULL OR #isDead1 = 0 OR #isDead2 = 0)
RETURN 1;
IF (#isDead1 = 1 AND #isDead2 = 1)
RETURN 0;
END
RETURN NULL;
END
I tried to convert it to a table-function, but it worked slowly:
ALTER FUNCTION dbo.GetIsDeadTableFunc (
#IdentityNumber1 nvarchar(9),
#FileId INT)
RETURNS TABLE AS RETURN
select (case when (b.MateIdentityNumber > 0 and b.MateIdentityNumber
not in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId))
then 2
when (b.MateIdentityNumber = 0
and DeathDate is null)
or (b.MateIdentityNumber > 0 and b.MateIdentityNumber in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId
and (DeathDate is null or DeathDate is not null))
and DeathDate is null)
or (b.MateIdentityNumber > 0 and b.MateIdentityNumber in (SELECT IdentityNumber1
from EDBNationalInsuranceMortgageLoad_tmp
where IsRowError=0
and FileId=#FileId
and DeathDate is null) -- אמור להיות עוד פונה והוא נמצא בקובץ חי
and DeathDate is not null) -- פונה 1 נפטר
then 1
else 0 end) as IsDead
from EDBNationalInsuranceMortgageLoad_tmp e
join MortgageReturnParticipationBase b on b.IdentityNumber = e.IdentityNumber1
WHERE e.IdentityNumber1 = #IdentityNumber1
and IsRowError=0
and FileId=#FileId
and b.MortgageReturnParticipationStatusId=1
GO

optimize complex stored procedure

I have a very complex stored procedure and i am not that strong in SQL, please any one who has a strong SQL expertise and can help me optimize or at least can give me a hint, the procedure selects the inbox messages from database for specific user and it contains many other parameters such as paging and categories and also language input and many other details:
ALTER PROCEDURE [dbo].[Inbox]
#ConfidentialityIds NVARCHAR(100) = '0,1,2,3',
#UrgencyIds NVARCHAR(100) = '0,1,2,3',
#CorrespondenceCategoryIds NVARCHAR(100) = '1,2,3,5,6,7',
#CorrespondenceExtendedCategoryIds NVARCHAR(MAX),
#IsPrivate bit = 0,
#IsSaved bit = 0,
#Importantance VARCHAR(10) = '0, 1',
#UserId uniqueidentifier,
#SelectedPage int = 1,
#PageSize int = 25,
#Now bigint,
#IsImpersonated bit,
#ActualLoggedInUserId uniqueidentifier,
#IsEnglish bit,
#OnlyArchived bit = null,
#replaceNameWithEntName bit,
#entityIds nvarchar(MAX),
#OnlyLate bit = 0,
#Statuses NVARCHAR(100) ='1,2,3,4,5',
#ApplyPageFilter bit = 1,
#IsBundled int,
#showArchivedInCCInbox bit = 0,
#appModuleId INT = 0
WITH RECOMPILE
As
BEGIN
SET transaction isolation level read uncommitted
DECLARE #lFirstRec INT, #lLastRec INT, #lTotalRows INT
SET #lFirstRec = ( #SelectedPage - 1 ) * #PageSize
SET #lLastRec = ( #SelectedPage * #PageSize + 1 )
SET #lTotalRows = #lFirstRec - #lLastRec + 1
DECLARE #isPersonalDelegationAvailable BIT = 0
IF EXISTS(
SELECT 1
FROM DelegatedToEntityUsers d
WHERE d.DelegatedToUserId = #ActualLoggedInUserId
AND d.DelegatedFromUserId = #UserId
AND
(
d.DelegatedToEntityId IS NULL OR d.DelegationType = 1
))
BEGIN
SET #isPersonalDelegationAvailable = 1
END
DECLARE #tblEntities TABLE(Value INT)
INSERT INTO #tblEntities
SELECT Value FROM SplitCommaUniqueValues(#entityIds)
Select * from (
Select (ROW_NUMBER() OVER (ORDER BY K.ActionDate DESC, K.CorrespondenceDate DESC)) AS RowIndex,
Count(*) over () AS TotalCount,*
from (
select (ROW_NUMBER() OVER (PARTITION BY CorrespondenceID Order by CorrespondenceID DESC)) AS CorrId, *
from (
SELECT Distinct * FROM
(
SELECT
CONVERT(VARCHAR(100), R.CorrespondenceActionRecipientID) Id,
A.CorrespondenceActionID ActionId,
(CASE WHEN R.RecipientType IS NULL THEN NULL ELSE CAST(RecipientType AS INT) END) RecipientType,
A.ActionTypeId,
(CASE when #IsEnglish = 1 then ATypes.FriendlyTextEN else ATypes.FriendlyTextAR end) ActionTypeName,
A.ActionCreatedByUserID SentById,
CASE
when #replaceNameWithEntName = 0 then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentByEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentByEntity.EntityNameEn else SentByEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentByEntity.EntityID in (SELECT Value FROM #tblEntities) then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
END SentByFrom,
A.WithDelegateFromUserID OnBehalfOfId,
ISNULL(WithDelegateFromUser.ShortName, WithDelegateFromUser.EmployeeName) OnBehalfOfName,
R.UserId SentToId,
CASE
when #replaceNameWithEntName = 0 then ISNULL(SentToUser.ShortName, SentToUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentToEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentToEntity.EntityID in (SELECT Value FROM #tblEntities) then isnull(ISNULL(SentToUser.ShortName, SentToUser.EmployeeName), case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end)
END SentToName,
R.EntityID SentToEntityId,
SentToEntity.EntityNameAR SentToEntityNameAR,
SentToEntity.EntityNameEN SentToEntityNameEN,
R.Seen,
(CASE WHEN MR.CorrespondenceActionRecipientID IS NOT NULL THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsReadByUser,
CAST(ISNULL(FollowedByUser.IsFollowedByUser, 0) AS BIT) IsFollowedByUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND UserId = #UserId AND AssignedByUserId IS NOT NULL) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowToUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND AssignedByUserId = #UserId) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowByUser,
A.CorrespondenceID,
A.ActionDate,
A.ActionDeadlineDate,
C.CompletionDate,
C.CorrespondenceDeadlineDate CorrDeadlineDate,
C.OwnerUserID CorrOwnerId,
C.ChildNo ChildNo,
OwnerUser.EmployeeName CorrOwnerName,
C.Important,
C.UrgencyId,
C.LetterCorrespondenceId,
(CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) UrgencyText,
C.ConfidentialityId,
(CASE when #IsEnglish = 1 then Confid.TextEN else Confid.TextAR end) ConfidentialityText,
C.CorrespondenceCategoryId CategoryId,
C.CorrespondenceClassificationID CorrespondenceClassificationID,
(CASE when #IsEnglish = 1 then CCat.TextEN else CCat.TextAR end) CategoryName,
CCat.ColorClass ColorClass,
C.Subject,
c.CorrespondenceFormula,
C.InternalSenderEntityId,
C.InternalRecipientEntityId,
C.[Sequence] [Sequence],
C.Year,
C.CompletionStatus Status,
Null Number,
(CASE WHEN (
(
(A.ActionDeadlineDate IS NOT NULL AND A.ActionDeadlineDate < #Now)
OR
(C.CorrespondenceDeadlineDate IS NOT NULL AND C.CorrespondenceDeadlineDate < #Now)
)
AND
C.[Closed-Archived] = 0) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsLate,
CAST(0 AS BIT) HasAnyEvents,
C.CreatedByUserId,
CreatedByUser.EmployeeName CreatedByUserName,
CAST(C.CorrespondenceDate AS VARCHAR(50)) CorrDate,
C.CorrespondenceDate,
C.[Closed-Archived] ClosedArchived,
C.IsSaved SavedActionTaken,
((CASE WHEN C.Important = 1 THEN CASE WHEN #IsEnglish = 1 THEN N'Important' ELSE N'هامة' END ELSE '' END) + (CASE WHEN C.Important = 1 AND C.UrgencyID <> 0 THEN CASE WHEN #IsEnglish = 1 THEN N' and ' ELSE N' و ' END ELSE '' END) + (CASE WHEN C.UrgencyID <> 0 THEN (CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) ELSE '' END)) ImportantUrgencyText,
CAST(C.IsAutoSaved AS BIT) IsAutoSaved,
-- *******************************************************************
rem.ReminderDate as CorrespondenceReminderDateTime,
remAction.ReminderDate as ActionReminderDateTime
FROM (
SELECT * FROM Correspondences CC
WHERE CC.IsDeleted = 0
AND CC.LetterCorrespondenceId IS NULL
AND (CC.ConfidentialityId IN (SELECT [Value] FROM SplitCommaUniqueValues(#ConfidentialityIds)))
AND
( #IsPrivate = 0 OR
(
#IsPrivate = 1 AND CC.IsForPresident = 1
)
)
AND
(
(CC.IsSaved = case when #IsSaved =1 then 1 else CC.IsSaved end)
)
AND (#appModuleId = 0 OR CC.AppModuleId = #appModuleId)
AND (CC.UrgencyID IN (SELECT value FROM SplitCommaUniqueValues(#UrgencyIds)))
AND (CC.Important IN (SELECT value FROM SplitCommaUniqueValues(#Importantance)))
AND CC.CompletionStatus IN(SELECT value FROM SplitComma(#Statuses))
) C
LEFT JOIN CorrespondenceExtendedDetails CorrExt
ON CorrExt.CorrespondenceID = C.CorrespondenceID
LEFT JOIN CorrespondenceActions A
ON C.CorrespondenceID = A.CorrespondenceID
AND A.IsDeleted = 0
AND A.ActionTypeID != 7 -- إنهاء التذكير
LEFT JOIN CorrespondenceActionRecipients R
ON A.CorrespondenceActionID = R.CorrespondenceActionID
AND (
R.AsCopy = 1
)
JOIN Urgencies U
ON C.UrgencyID = U.ID
JOIN ActionTypes ATypes
ON A.ActionTypeID = ATypes.ID
JOIN CorrespondenceCategories CCat
ON C.CorrespondenceCategoryId = CCat.ID
JOIN Confidentialities Confid
ON C.ConfidentialityID = Confid.ID
LEFT JOIN Users ActionCreatedByUser
ON A.ActionCreatedByUserID = ActionCreatedByUser.UserId
LEFT JOIN Users WithDelegateFromUser
ON A.WithDelegateFromUserID = WithDelegateFromUser.UserID
LEFT JOIN Entities SentByEntity
ON A.ActionCreatedByUserEntityId = SentByEntity.EntityID
LEFT JOIN Users SentToUser
ON R.UserId = SentToUser.UserId
LEFT JOIN Entities SentToEntity
ON R.EntityID = SentToEntity.EntityID
LEFT JOIN Users OwnerUser
ON C.OwnerUserID = OwnerUser.UserId
LEFT JOIN Users CreatedByUser
ON C.CreatedByUserID = CreatedByUser.UserId
LEFT JOIN MarkAsReads MR
ON R.CorrespondenceActionRecipientID = MR.CorrespondenceActionRecipientID
AND MR.UserId = #UserId
OUTER APPLY
(
SELECT TOP 1 1 IsFollowedByUser
FROM CorrespondenceFollowups CF
WHERE CF.CorrespondenceId = C.CorrespondenceID
AND CF.UserId = #UserId
AND CF.AssignedByUserId IS NULL
) FollowedByUser
-- *******************************************************************
LEFT JOIN LinkedCorrespondenceSchedules CS on CS.CorrespondenceID = C.CorrespondenceID
LEFT JOIN Reminder rem on rem.ReferenceId=C.CorrespondenceID AND rem.ReferenceType = 1 AND rem.CreatedByUserId=#UserId AND (rem.[Status] = 1 OR rem.[Status] = 2)
Left JOIN Reminder remAction on remAction.ReferenceId = A.CorrespondenceActionID AND remAction.ReferenceType = 2 AND remAction.CreatedByUserId=#UserId AND (remAction.[Status] = 1 OR remAction.[Status] = 2)
-- *******************************************************************
WHERE (
(C.CorrespondenceCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceCategoryIds)) AND CorrExt.CorrespondenceExtendedCategoryId IS NULL)
OR (CorrExt.CorrespondenceExtendedCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceExtendedCategoryIds)))
)
AND
(
-- Personal
(
(
(#IsImpersonated = 0 AND R.UserId = #UserId)
OR
(#IsImpersonated = 1 AND R.UserId = #UserId AND #isPersonalDelegationAvailable = 1)
)
AND R.RecipientType = 1 AND R.UserId Is Not null
)
OR
-- Me as Manager (Impersonation mode handled from code by sending the proper Entity Ids.
(
(R.EntityID IN (SELECT Value FROM #tblEntities) AND R.EntityID Is Not null AND R.RecipientType != 1)
)
)
AND C.[Closed-Archived] = Case When #showArchivedInCCInbox = 1 Then 0 Else C.[Closed-Archived] End
AND R.UserTokeAction = 0
AND NOT EXISTS (
SELECT 1 FROM Correspondences CC
INNER JOIN CorrespondenceLinks CL
ON CC.CorrespondenceID = CL.LinkedCorrespondenceID AND CC.CorrespondenceID = C.CorrespondenceID AND CL.LinkTypeID = #IsBundled
)
) T
WHERE T.LetterCorrespondenceId is null
) as ttt
) K where CorrId = 1
)N where (#ApplyPageFilter = 0 OR ( RowIndex > #lFirstRec AND RowIndex < #lLastRec))
Order by
ActionDate DESC, CorrespondenceDate
option(recompile)
END

IF ELSE in SQL Server stored procedure

I'm trying to accomplish the IF ELSE statement in a SQL Server stored procedure but it seems that it won't follow the condition. I tried to declare a static value for me to check it but its still the same. My problem is it wont go to ELSE even if the condition is wrong
Here's the code:
ALTER PROCEDURE [dbo].[Amount_Computation]
(#OfficeID int,
#AccountID int,
#Amount int,
#NoOfMonths int,
#Percentage int,
#isRoundOf int,
#MaxAmount int,
#EmployeeType int)
AS
declare #TotalAmount table(TotalAmount int)
declare #Casual table(CasualSalary int, OfficeID int)
declare #Regular table(RegularSalary int, OfficeID int)
declare #basic int
BEGIN
SELECT
#Amount = 1, #OfficeID = 72,
#AccountID = 733, #Amount = 0,
#NoOfMonths = 12, #Percentage = 1.25,
#isRoundOf = 1, #MaxAmount = 35000,
#EmployeeType = 1
IF(#Amount = 0)
BEGIN
INSERT INTO #Casual
SELECT
CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic * 22 > #MaxAmount) then #MaxAmount ELSE Basic * 22 END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic * 22 > #MaxAmount) then #MaxAmount ELSE Basic * 22 END) AS INT))) - 3)) + '000' ) AS INT ) * #Percentage / 100 * #NoOfMonths as Casual,
a.OfficeID
FROM
pmis.dbo.vw_RGPermanentAndCasual as a
LEFT JOIN
ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID
WHERE
a.OfficeID = #OfficeID AND a.EmploymentGroup = '2'
INSERT INTO #Regular
SELECT
CAST(((select LEFT(CONVERT(nvarchar,CAST((Case when (basic > #MaxAmount) then #MaxAmount ELSE Basic END) AS INT)),LEN(CONVERT(nvarchar,CAST((Case when (basic > #MaxAmount) then #MaxAmount ELSE Basic END) AS INT))) - 3)) + '000' ) AS INT ) * #Percentage / 100 * #NoOfMonths as Regular,
a.OfficeID
FROM
pmis.dbo.vw_RGPermanentAndCasual as a
LEFT JOIN
ifmis.dbo.tbl_R_BMSOffices as b ON b.PMISOfficeID = a.OfficeID
WHERE
a.OfficeID = #OfficeID AND a.EmploymentGroup = '1'
INSERT INTO #TotalAmount
SELECT
SUM(CasualSalary) + SUM(RegularSalary)
FROM
#Casual as a
LEFT JOIN
#Regular as b ON b.OfficeID = a.OfficeID
END
ELSE IF(#Amount = 1)
BEGIN
INSERT INTO #TotalAmount
SELECT SUM(CasualSalary) as ELSE_IF
FROM #Casual
END
END
/**SELECT CasualSalary FROM #Casual
SELECT RegularSalary FROM #Regular **/
SELECT TotalAmount FROM #TotalAmount
EDIT: Select #Amount should be
SELECT #Amount = 1,#OfficeID = 72,#AccountID = 733, #NoOfMonths = 12, #Percentage = 1.25, #isRoundOf = 1, #MaxAmount = 35000, #EmployeeType = 1
As you noticed yourself - #Amount is listed twice in your SELECT list, with two distinct values.
Easy fix. :)

how to set default value in a output parameter

in my following query i want to set 0, 0, 0 in #TMarks, #OMarks, #Percentage respectively if the select statement used with them returns nothing
create procedure [dbo].[TestRecordSelectMInfo]
#GRNo varchar(4),
#SessionId numeric(1),
#TestTypeId numeric(1),
#TMarks int output,
#OMarks numeric(4) output,
#Percentage numeric(4) output,
#Grade varchar(4) output
as
begin
SELECT Subjects.Subject, Marks.TotalMarks, Marks.PassingMarks, TestRecord.Marks, Result = case when TestRecord.Marks = 'A' then 'A' else case when cast(TestRecord.Marks as numeric) < Marks.PassingMarks then 'F' else 'P' end end FROM Subjects INNER JOIN Marks ON Subjects.SubjectId = Marks.SubjectId INNER JOIN TestRecord ON Subjects.SubjectId = TestRecord.SubjectId AND Marks.TestTypeId = TestRecord.TestTypeId where TestRecord.SessionId = #SessionId and TestRecord.TestTypeId = #TestTypeId and TestRecord.GRNo = #GRno
set #TMarks = (select sum(Marks.TotalMarks) from Marks inner join TestRecord on Marks.TestTypeId = TestRecord.TestTypeId and Marks.SubjectId = TestRecord.SubjectId where TestRecord.SessionId = #SessionId and TestRecord.TestTypeId = #TestTypeId and TestRecord.GRNo = #GRNo and TestRecord.Marks <> 'A' and cast(TestRecord.Marks as numeric) > Marks.PassingMarks )
set #OMarks = (select sum(cast(TestRecord.Marks as numeric)) from Marks inner join TestRecord on Marks.TestTypeId = TestRecord.TestTypeId and Marks.SubjectId = TestRecord.SubjectId where TestRecord.SessionId = #SessionId and TestRecord.TestTypeId = #TestTypeId and TestRecord.GRNo = #GRNo and TestRecord.Marks <> 'A' and cast(TestRecord.Marks as numeric) > Marks.PassingMarks)
set #Percentage = #OMarks / #TMarks * 100;
set #Grade = case
when #Percentage < 50
then
'NIL'
else
case
when #Percentage < 60
then
'C'
else
case
when #Percentage < 70
then
'B'
else
case
when #Percentage < 80
then
'A'
else
case
when #Percentage <= 100
then
'A+'
else
'FAIL'
end
end
end
end
end
end
GO
EDIT: An aggregate without a group by returns null for an empty set. You could work around this with insull:
select #TMarks = IsNull(sum(Marks.TotalMarks),0)
from Marks
inner join TestRecord
on Marks.TestTypeId = TestRecord.TestTypeId
and Marks.SubjectId = TestRecord.SubjectId
where TestRecord.SessionId = #SessionId
and TestRecord.TestTypeId = #TestTypeId
and TestRecord.GRNo = #GRNo
and TestRecord.Marks <> 'A'
and cast(TestRecord.Marks as numeric) > Marks.PassingMarks