Case when in Select, Left Join and Group By - sql

how can i archive the following?
If #chk = 0 then include 4th Column in result else keep only 3 Columns,
and if 4th Column is selected then Left join is needed for that 4th column,
and include that 4th column in group by
DECLARE #chk AS INT= 0;
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN #chk = 0 THEN c.ledgername END (is it possilbe to completly do not have this column if #chk <> 0)
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if #chk=0, same logic is there in above select statement
GROUP BY A.LedgerID,
B.LedgerCity;
C.LedgerName; -- this 3rd group required only if #chk=0
some posts suggested how to use case when in Group by. I tried "group by case when #chk=0 then a.Ledgerid,b.Ledgercity,c.LedgerName else a.Ledgerid,b.Ledgercity END; but this did not work

Use IF .. ELSE block
IF #chk = 0
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN #chk = 0 THEN c.ledgername END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if #chk=0, same logic is there in above select statement
GROUP BY A.LedgerID, B.LedgerCity, C.LedgerName;
END
ELSE
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
GROUP BY A.LedgerID, B.LedgerCity;
END

If you are sure, that no one from outside of the database can run your query and perform sql-injection, just use the simple dynamic-sql statement
DECLARE #sql AS NVARCHAR(MAX);
DECLARE #chk AS INT= 0;
set #sql = N'SELECT a.Ledgerid,
b.LedgerCity, ' +
CASE WHEN #chk = 0 THEN 'SUM(a.TotalAmount) ' ELSE 'SUM(a.NetAmount) ' END +
CASE WHEN #chk = 0 THEN ', c.ledgername ' ELSE ' ' END +
'FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID ' +
CASE WHEN #chk=0 THEN 'LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID ' ELSE '' END +
'GROUP BY A.LedgerID,
B.LedgerCity' +
CASE WHEN #chk = 0 THEN ', C.LedgerName;' ELSE ';' END;
exec sp_executesql #sql

Related

Best performance for paging query when using multiple statements in sql?

It is a bit complicated query but let me elaborate,
i have got multiple filter parameters in my procedure,
also a view named Vw1 and its regarded my main object in query that most of the filter parameters are filtered against this view that is located in another server,then i need to compare this view to another table and check two sides columns for possible conflict and then check if there is any conflict.
you can see my query below
ALTER PROC [dbo].[spGetAyandehVagozariWithConflict]
#Take INT,
#Skip INT,
#FromVagozariDate NVARCHAR(10),
#ToVagozariDate NVARCHAR(10),
#OrderBankCode NVARCHAR(4)=null,
#OrderBrCode NVARCHAR(7)=null,
#BenefBrCode NVARCHAR(4)=null,
#FromAmount NVARCHAR(50)=null,
#ToAmount NVARCHAR(50)=null,
#CheqSerie NVARCHAR(50)=null,
#CheqSerial NVARCHAR(10)=null,
#CheqStatus NVARCHAR(4)=null,
#CreditorNationalCode VARCHAR(20)=NULL,
#CheqType NVARCHAR(4)=null,
#BenefAccn NVARCHAR(13)=null,
#FromMatDate NVARCHAR(10)=null,
#ToMatDate NVARCHAR(10)=null,
#FromTaeenVaziatDate NVARCHAR(10)=null,
#ToTaeenVaziatDate NVARCHAR(10)=NULL,
#HasConflict VARCHAR(4)=null,
#TotalCnt INT OUTPUT,
#SUM BIGINT OUTPUT
AS
BEGIN
DECLARE #Query NVARCHAR(MAX)=''
IF(NULLIF(#FromVagozariDate,'') IS null)
SET #FromVagozariDate='NULL'
IF(NULLIF(#ToVagozariDate,'') IS null)
SET #ToVagozariDate='NULL'
IF(NULLIF(#OrderBrCode,'') IS null)
SET #OrderBrCode='NULL'
IF(NULLIF(#OrderBankCode,'') IS null)
SET #OrderBankCode='NULL'
IF(NULLIF(#BenefBrCode,'') IS null)
SET #BenefBrCode='NULL'
IF(NULLIF(#FromAmount,'') IS null)
SET #FromAmount='NULL'
IF(NULLIF(#ToAmount,'') IS null)
SET #ToAmount='NULL'
IF(NULLIF(#CheqSerie,'') IS null)
SET #CheqSerie='NULL'
IF(NULLIF(#CheqSerial,'') IS null)
SET #CheqSerial='NULL'
IF(NULLIF(#CheqStatus,'') IS null)
SET #CheqStatus='NULL'
IF(NULLIF(#CheqType,'') IS null)
SET #CheqType='NULL'
IF(NULLIF(#BenefAccn,'') IS null)
SET #BenefAccn='NULL'
IF(NULLIF(#ToMatDate,'') IS null)
SET #ToMatDate='NULL'
IF(NULLIF(#FromMatDate,'') IS null)
SET #FromMatDate='NULL'
IF(NULLIF(#FromTaeenVaziatDate,'') IS null)
SET #FromTaeenVaziatDate='NULL'
IF(NULLIF(#ToTaeenVaziatDate,'') IS null)
SET #ToTaeenVaziatDate='NULL'
IF(NULLIF(#HasConflict,'') IS null)
SET #HasConflict='NULL'
IF(NULLIF(#CreditorNationalCode,'') IS null)
SET #CreditorNationalCode='NULL'
IF #FromVagozariDate<>'NULL'
BEGIN
SET #FromVagozariDate=REPLACE(#FromVagozariDate,'/','')
END
IF #ToVagozariDate<>'NULL'
BEGIN
SET #ToVagozariDate=REPLACE(#ToVagozariDate,'/','')
END
IF #FromMatDate<>'NULL'
BEGIN
SET #FromMatDate=REPLACE(#FromMatDate,'/','')
END
IF #ToMatDate<>'NULL'
BEGIN
SET #ToMatDate=REPLACE(#ToMatDate,'/','')
END
IF #FromTaeenVaziatDate<>'NULL'
BEGIN
SET #FromTaeenVaziatDate=REPLACE(#FromTaeenVaziatDate,'/','')
SET #FromTaeenVaziatDate=SUBSTRING(#FromTaeenVaziatDate,3,6)
END
IF #ToTaeenVaziatDate<>'NULL'
BEGIN
SET #ToTaeenVaziatDate=REPLACE(#ToTaeenVaziatDate,'/','')
SET #ToTaeenVaziatDate=SUBSTRING(#ToTaeenVaziatDate,3,6)
END
IF #OrderBankCode<>'NULL'
BEGIN
--SET #OrderBankCode='0'+#OrderBankCode;
SET #OrderBankCode=dbo.LeftPad(#OrderBankCode,'0',3)
END
IF(#BenefBrCode<>'NULL')
BEGIN
SET #BenefBrCode=dbo.LeftPad(#BenefBrCode,'0',4)
END
IF(#OrderBrCode<>'NULL')
BEGIN
SET #OrderBrCode=dbo.LeftPad(#OrderBrCode,'0',4)
END
SET #Query=#Query+N'
SELECT *
INTO #Vw1
FROM [LinkedServer].DbName.dbo.Vw1 vd
where (vd.mat_date BETWEEN '+''''+#FromMatDate+''''+' AND'+''''+ #ToMatDate+''''+' OR ('+''''+#FromMatDate+''''+' =''NULL'' AND '+''''+#ToMatDate+''''+' =''NULL'' )) AND
(dbo.LeftPad(vd.order_bank_code,''0'',3)= '+''''+#OrderBankCode+''''+' OR '+''''+#OrderBankCode+''''+' =''NULL'') AND
(dbo.LeftPad(vd.order_brcode,''0'',4)= '+''''+#OrderBrCode+''''+' OR '+''''+#OrderBrCode+''''+' =''NULL'') AND
(dbo.LeftPad(vd.Benef_br_code,''0'',4)= '+''''+#BenefBrCode+''''+' OR '+''''+#BenefBrCode+''''+' =''NULL'') AND
(substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10) BETWEEN '+''''+#FromAmount+''''+' AND '+''''+#ToAmount+''''+' OR ('+''''+#FromAmount+''''+' =''NULL'' AND '+''''+#ToAmount+''''+' =''NULL'')) AND
(RTRIM(LTRIM(vd.chq_serie))= '+''''+#CheqSerie+''''+' OR '+''''+#CheqSerie+''''+' =''NULL'') AND
(RTRIM(LTRIM(vd.chq_serial))= '+''''+#CheqSerial+''''+' OR '+''''+#CheqSerial+''''+' =''NULL'') AND
(vd.Chq_stat= '+''''+#CheqStatus+''''+' OR '+''''+#CheqStatus+''''+' in (''NULL'',''-1'')) AND
(vd.chq_type= '+''''+#CheqType+''''+' OR '+''''+#CheqType+''''+' =''NULL'') AND
(vd.benef_acno= '+''''+#BenefAccn+''''+' OR '+''''+#BenefAccn+''''+' =''NULL'') AND
((vd.taeen_vaziat_date is null AND ('+''''+#CheqStatus+''''+'=''-1'')) or('+''''+#CheqStatus+''''+'<>''-1'') ) AND
(vd.vagozari_date BETWEEN '+''''+#FromVagozariDate+''''+' AND '+''''+#ToVagozariDate+''''+' OR ('+''''+#FromVagozariDate+''''+' =''NULL'' AND '+''''+#ToVagozariDate+''''+' =''NULL'')) AND
(vd.taeen_vaziat_date BETWEEN '+''''+#FromTaeenVaziatDate+''''+' AND '+''''+#ToTaeenVaziatDate+''''+' OR ('+''''+#ToTaeenVaziatDate+''''+' =''NULL'' AND '+''''+#FromTaeenVaziatDate+''''+' =''NULL''))
order by system_no
select distinct cast(benef_acno as bigint) benef_acno
into #acno
from #Vw1
select ACNO,CUSTNO
into #ACTINFO
from [LinkServer1].[Db1].[dbo].[ACTINFO] af
where accno_id in (select * from #acno)
select [ECONOMIC-CODE],CUSTNO,FIRSTNAME +'' ''+LASTNAME CUSTNAME
into #CUSTINFO
from [LinkServer1].[Db1].[dbo].[CUSTINFO]
where CustNo_Id in (select cast(CUSTNO as bigint) from #ACTINFO)
SELECT
vd.*,
ct.Title CheqTypeTitle,
af.CUSTNO,cf.CUSTNAME,
--'''' as CUSTNO,'''' CUSTNAME,
cs.Status CheqStatusTitle,
av.Id AyandehVagozariId,
p.ParticipantName BenefBankName,
CASE WHEN ISNULL(vd.vagozari_date,'''') <> COALESCE(REPLACE(av.VagozariDate,''/'',''''),vd.vagozari_date,'''') THEN 1 ELSE 0 END VagozariDateHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.order_bank_code,''0'',3),'''') <> COALESCE(av.Order_Bank_Code,dbo.LeftPad(vd.order_bank_code,''0'',3),'''') THEN 1 ELSE 0 END OrderBankCodeHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.order_brcode,''0'',4),'''') <> COALESCE(av.Order_brCode,dbo.LeftPad(vd.order_brcode,''0'',4),'''') THEN 1 ELSE 0 END OrderBrCodeHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.Benef_br_code,''0'',4),'''') <> COALESCE(av.Benef_Br_Code,dbo.LeftPad(vd.Benef_br_code,''0'',4),'''') THEN 1 ELSE 0 END BenefBrCodeHasConflict,
CASE WHEN ISNULL(substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10),'''') <> COALESCE(av.Amount,substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10),'''') THEN 1 ELSE 0 END AmountHasConflict,
CASE WHEN ISNULL(vd.chq_serie,'''') <> COALESCE(av.Chq_serie,vd.chq_serie,'''') THEN 1 ELSE 0 END CheqSerieHasConflict,
CASE WHEN ISNULL(RTRIM(LTRIM(vd.chq_serial)),'''') <> COALESCE(av.Chq_Serial,RTRIM(LTRIM(vd.chq_serial)),'''') THEN 1 ELSE 0 END CheqSerialHasConflict,
CASE WHEN ISNULL(vd.chq_type,'''') <> COALESCE(av.Chq_Type,vd.chq_type,'''') THEN 1 ELSE 0 END CheqTypeHasConflict,
CASE WHEN ISNULL(vd.benef_acno,'''') <> COALESCE(av.Benef_Acno,vd.benef_acno,'''') THEN 1 ELSE 0 END BenefAcnoHasConflict,
CASE WHEN ISNULL(vd.mat_date,'''') <> COALESCE(REPLACE(av.Mat_Date,''/'',''''),vd.mat_date,'''') THEN 1 ELSE 0 END MatDateHasConflict,
CASE WHEN ISNULL(cf.CUSTNO,'''') <> COALESCE(av.CUSTNO,cf.CUSTNO COLLATE DATABASE_DEFAULT,'''') THEN 1 ELSE 0 END CustNoHasConflict,
--CASE WHEN ISNULL(vd.taeen_vaziat_date,'''') <> COALESCE(av.Taeen_Vaziat_Date,vd.taeen_vaziat_date,'''') THEN 1 ELSE 0 END TaeenVaziatDateHasConflict,
0 as TaeenVaziatDateHasConflict,
CASE WHEN ISNULL(vd.Chq_stat,'''') <> COALESCE(av.Chq_Status,vd.Chq_stat,'''') THEN 1 ELSE 0 END CheqStatusHasConflict
--0 as VagozariDateHasConflict,
--0 as OrderBankCodeHasConflict,
--0 as OrderBrCodeHasConflict,
--0 as BenefBrCodeHasConflict,
--0 as AmountHasConflict,
--0 as CheqSerieHasConflict,
--0 as CheqSerialHasConflict,
--0 as CheqTypeHasConflict,
--0 as BenefAcnoHasConflict,
--0 as MatDateHasConflict,
--0 as TaeenVaziatDateHasConflict
INTO #temp
FROM #vw_faranam_vagozari_chakavak vd
LEFT JOIN #ACTINFO af on vd.benef_acno=af.ACNO COLLATE Arabic_CI_AS
LEFT JOIN #CUSTINFO cf on af.CUSTNO=cf.CUSTNO COLLATE Arabic_CI_AS
LEFT JOIN [AyandehVagozari] av ON av.SystemNo=vd.system_no
LEFT JOIN [Cheque_Type_Biha] ct ON ct.Code=vd.chq_type
LEFT JOIN [ChequeStatusForBiha] cs ON cs.Id=vd.Chq_stat
LEFT JOIN [Participant] p ON ''0''+p.ParticipantCode=vd.order_bank_code
WHERE (cf.[ECONOMIC-CODE]= '+''''+#CreditorNationalCode+''''+' OR '+''''+#CreditorNationalCode+''''+' =''NULL'')
order by vd.system_no
DELETE t FROM(
SELECT *,ROW_NUMBER() OVER(partition by system_no order by AyandehVagozariId desc) rn FROM
#temp
)t
where rn>1
SELECT *,
case when (VagozariDateHasConflict=1 or OrderBankCodeHasConflict=1 or OrderBrCodeHasConflict =1 OR BenefBrCodeHasConflict=1
or AmountHasConflict=1 or CheqSerieHasConflict=1 or CheqSerialHasConflict=1 or CustNoHasConflict=1
or CheqStatusHasConflict=1 or CheqTypeHasConflict=1 or BenefAcnoHasConflict=1 or MatDateHasConflict=1 or TaeenVaziatDateHasConflict=1)
then 1 else 0 end HasConflict
INTO #TmpResult
FROM #temp
order by system_no
--here is where i filter my last parameter but it seems too late..because alot of records already involved !
SELECT *,ROW_NUMBER() over (ORDER BY system_no) RowNumber
into #finalTemp
FROM
#TmpResult
where (HasConflict=1 and '+''''+#HasConflict+''''+'=''1'')
OR (HasConflict=0 and '+''''+#HasConflict+''''+'=''0'')
OR ('+''''+#HasConflict+''''+'=''NULL'')
order by system_no
SELECT #Total=##ROWCOUNT
select #Sum=isnull(SUM(cast(amount as bigint)),0) from
#finalTemp
select * from
#finalTemp
WHERE RowNumber >'+CAST(#Skip AS NVARCHAR(10))+' AND RowNumber<=('+CAST(#Skip+#Take AS NVARCHAR(10))+')
'
PRINT #Query
EXEC sp_executesql #Query,N'#Total int output,#Sum bigint output',#TotalCnt OUTPUT,#SUM OUTPUT
END
due to performance issues i had to write it in dynamic way,But the problem is that i could not wrap my head around paging in this query, bacause as you see i should put paging line in the end of query because #HasConflict parameters exist and i cannot check it earlier,and in this way my paging seems pointless because i'm dealing with huge load of data ...
also i cannot use offset for paging because my sql version is too old ...

How to use CASE statement when to local variables for multiple conditions

on basis of local variable value I want to make condition on a particular column in select statement.
declare #str VARCHAR(50)='ProjectCostAll'
SELECT pm.intProjectID,pm.strProjectName,im.intInvID,im.strInvNo
FROM dbo.tblProjectMaster PM
LEFT JOIN dbo.tblInvoiceDetails ID ON id.intProjectID=pm.intProjectID
LEFT JOIN dbo.tblInvoiceMaster IM ON im.intInvID=id.intInvID
WHERE CASE
WHEN #str ='ProjectCostInv' THEN
ISNULL(IM.intInvID,0) <> 0
WHEN #str ='ProjectCostNotInv' THEN
ISNULL(IM.intInvID,0) = 0
ELSE
ISNULL(IM.intInvID,0) >= 0
end
WHERE (#str = 'ProjectCostInv' AND IM.intInvID <> 0)
OR (#str = 'ProjectCostNotInv' AND ISNULL(IM.intInvID,0) = 0)
OR (#str not in ('ProjectCostInv', 'ProjectCostNotInv') AND ISNULL(IM.intInvID,0) >= 0)
but the overall approach is bad for performance.
I don't eval the meaning of your case result but out of this
if you want see the result in select you should use the case in select not in where
SELECT pm.intProjectID,pm.strProjectName,im.intInvID,im.strInvNo,
CASE
WHEN #str ='ProjectCostInv' THEN '<> 0'
WHEN #str ='ProjectCostNotInv' THEN '0'
ELSE '>= 0'
end my_result
FROM dbo.tblProjectMaster PM
LEFT JOIN dbo.tblInvoiceDetails ID ON id.intProjectID=pm.intProjectID
left JOIN dbo.tblInvoiceMaster IM ON im.intInvID=id.intInvID

SQL Query filter with custom field

Below code are use to detect if there exist userid=1 followerid=2 AND userid=2 followerid=1, then the custom column 'bool' will return TRUE.
However, somehow i can't get rid the extra row.
Any better suggestion or recommendations are appreciated. Thank you.
SELECT DISTINCT a.id, a.userid, a.followerid,
CASE WHEN b.userid=a.followerid AND b.followerid=a.userid
THEN 'TRUE' ELSE 'FALSE' END AS bool
FROM tableUserfollow AS a, tableUserfollow AS b
where a.userid=1
tableUserFollow:
id userid followerid
1 1 2
2 3 4
3 1 4
4 5 1
5 2 1
The output result should be:
1 1 2 TRUE
3 1 4 FALSE
instead of this:
1 1 2 FALSE
1 1 2 TRUE
3 1 4 FALSE
If you want to know if the reciprocal relationship is present, then I think the simplest way is using a correlated subquery, left join, or outer apply:
select uf.*, coalesce(flag, 'FALSE') as
from tableUserfollow uf outer apply
(select 'TRUE' as flag
from tableUserfollow uf2
where uf2.userId = uf.followerId and uf2.follwerId = uf.userId
) f;
The join would look like:
select uf.*,
(case when uf2.userId is null then 'FALSE' else 'TRUE' end)
from tableUserfollow uf left join
tableUserfollow uf2
on uf2.userId = uf.followerId and uf2.follwerId = uf.userId
DECLARE #sql AS nvarchar(MAX);
DECLARE #Search AS nvarchar(MAX);
DECLARE #AllFiels Varchar(max);
DECLARE #FixedField Varchar(max);
SET #FixedField=( SELECT
ISNULL(( STUFF(
(
SELECT ', '+(a.value) FROM vwCustomColumns a
WHERE a.Name IN (SELECT items FROM dbo.Split(CustomReports.ReportFixedFields,',') )
FOR XML path('')
)
, 1,1,'')) ,'cR.ContractID [Contract ID]') FixedField
FROM CustomReports WHERE CustomReportId=#CustomReportId )
SET #AllFiels=#FixedField;
SET #sql ='SELECT count(*) OVER() AS Maxcount ,'+#AllFiels+'
FROM vwRequestLatest cR
INNER JOIN MasterUsers ON MasterUsers.UsersId = cR.Addedby
LEFT OUTER JOIN RequestTemplate cte ON cte.ContractTemplateId=cR.RequestTemplateId
LEFT OUTER JOIN CountryMaster co ON co.CountryId=cR.CountryId
ORDER BY
';
IF (#SortColumn = '')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
ELSE IF (#SortColumn = 'Request ID')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
SET #sql =#sql +'OFFSET ( '+CONVERT(VARCHAR(100),#PageNo)+' - 1 ) * '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS FETCH NEXT '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS ONLY'
EXEC(#sql);

How to Check Parameter is not null in sql server?

I have a stored procedure. In this stored procedure I have to check that a particular parameter is not null. How can I do this? I wrote this:
ALTER PROCEDURE [dbo].[GetReelListings]
#locationUrlIdentifier VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
declare #Sql varchar(max)=''
SET #Sql = 'SELECT CategoryName, CategoryUrlIdentifier, LocationUrlIdentifier, Directory.* FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Category.Name ORDER BY CASE WHEN '''+ #locationUrlIdentifier + ''' = Location.UrlIdentifier THEN 1 ELSE CASE WHEN ''' + #locationUrlIdentifier + ''' IS NULL AND Directory.LocationId IS NULL THEN 0 ELSE 2 END END, Directory.SortOrder ) AS ''RowNo'', Category.Name AS CategoryName, Category.UrlIdentifier AS CategoryUrlIdentifier, dbo.Location.UrlIdentifier AS LocationUrlIdentifier, Directory.DirectoryId, CASE WHEN ''' + #locationUrlIdentifier + ''' = Location.UrlIdentifier THEN 1 ELSE CASE WHEN ''' + #locationUrlIdentifier + ''' IS NULL AND Directory.LocationId IS NULL THEN 0 ELSE 2 END END AS CategoryOrder FROM dbo.Directory INNER JOIN dbo.Category ON Directory.CategoryId = Category.CategoryId LEFT OUTER JOIN dbo.Location ON dbo.Directory.LocationId = location.Location_ID ) AS content INNER JOIN dbo.Directory ON content.DirectoryId = Directory.DirectoryId WHERE content.RowNo =1 '
if (#locationUrlIdentifier is null)
begin
SET #Sql = #Sql + ' and 1=1'
end
else
begin
SET #Sql = #Sql + ' and CategoryOrder = 1 '
end
print #SQl
EXECUTE (#Sql)
END
This will work in SQL but this will return a null Dataset in Codebehind.
Whenever you join strings and NULLs together, the result is NULL. By the time you're asking about whether the variable is NULL, you've already done this:
' + #locationUrlIdentifier + '
Several times. If it's NULL, so will #Sql be.
You might want to consider using COALESCE to replace the NULL with a suitable replacement (e.g. an empty string):
' + COALESCE(#locationUrlIdentifier,'') + '
You also still have a logic error on your final construction. If the variable is NULL, you'll have a where clause saying:
WHERE content.RowNo =1 1=1
Which isn't valid. I don't think you should be appending anything.
I'm also not clear on why you're doing this as dynamic SQL. The below seems to be an equivalent query which can be executed directly:
SELECT
CategoryName,
CategoryUrlIdentifier,
LocationUrlIdentifier,
Directory.*
FROM
(SELECT
ROW_NUMBER() OVER (
PARTITION BY Category.Name ORDER BY
CASE
WHEN #locationUrlIdentifier = Location.UrlIdentifier THEN 1
WHEN #locationUrlIdentifier IS NULL AND Directory.LocationId IS NULL THEN 0
ELSE 2
END,
Directory.SortOrder
) AS RowNo,
Category.Name AS CategoryName,
Category.UrlIdentifier AS CategoryUrlIdentifier,
dbo.Location.UrlIdentifier AS LocationUrlIdentifier,
Directory.DirectoryId,
CASE
WHEN #locationUrlIdentifier = Location.UrlIdentifier THEN 1
WHEN #locationUrlIdentifier IS NULL AND Directory.LocationId IS NULL THEN 0
ELSE 2
END AS CategoryOrder
FROM
dbo.Directory
INNER JOIN
dbo.Category
ON
Directory.CategoryId = Category.CategoryId
LEFT OUTER JOIN
dbo.Location
ON
dbo.Directory.LocationId = location.Location_ID
) AS content
INNER JOIN
dbo.Directory
ON
content.DirectoryId = Directory.DirectoryId
WHERE
content.RowNo =1 and
(#locationUrlIdentifier or CategoryOrder = 1)
You can do it just in ONE query:
Select Query ...where ...
and ((#locationUrlIdentifier is null) or (CategoryOrder = 1))
You can use NULLIF instead of IS NULL
Refer : Check if a parameter is null or empty in a stored procedure
http://msdn.microsoft.com/en-us/library/ms177562.aspx
Alternatively you can use ISNULL() check and then change the null to empty string
IF (ISNULL(#locationUrlIdentifier,'') = '')
OR even before this check you can use ISNULL() to convert from NULL to empty string if it persists to be a problem

Assign to a T-SQL variable from a CASE statement

I'd like to assign some variables inside a query that uses CASE statements for it's columns. Not quite sure how to do this, having trouble finding the right syntax.
This is what I have so far, but it's got syntax errors.
-- set #theID and #theName with their appropriate values
select top (1)
#theID = (Case when B.ID IS NULL then A.ID else B.ID END) ,
#theName = (Case when B.Name IS NULL then A.Name else B.Name END)
from B left join A on A.ID = B.ID where ...
What's the correct place/way to stick those variables in there?
The example you've given should work. You can assign to variables from a case statement. Just pretend that the entire CASE..WHEN..THEN..ELSE..END block is a field. Here is a generic example:
declare #string1 nvarchar(100) = null
declare #string2 nvarchar(100) = null
select
#string1 = case when 1=1 then 'yes' else 'no' end
,#string2 = case when 1=0 then 'yes' else 'no' end
print 'string1 = ' + #string1
print 'string2 = ' + #string2
Gives:
string1 = yes
string2 = no
Can you tell us what specific error(s) you are getting?
You could probably do this more easily using ISNULL or COALESCE:
select top (1)
#theID = ISNULL(B.ID, A.ID),
#theName = ISNULL(B.Name, A.Name),
from B left join A on A.ID = B.ID where ...
DECLARE #SmallBlindSeatId INT
DECLARE #BigBlindSeatId INT
DECLARE #DealerSeatId INT
DECLARE #NextTurn INT
SELECT #DealerSeatId=( CASE WHEN BlindsInfo=1 THEN SeatId ELSE #DealerSeatId END ),
#SmallBlindSeatId=( CASE WHEN BlindsInfo=2 THEN SeatId ELSE #SmallBlindSeatId END),
#BigBlindSeatId=( CASE WHEN BlindsInfo=3 THEN SeatId ELSE #BigBlindSeatId END),
#NextTurn=( CASE WHEN NEXTTURN=1 THEN SeatId ELSE #NextTurn END)
FROM ABC WHERE TESTCASEID=1
PRINT(#DealerSeatId)
PRINT(#SmallBlindSeatId)
PRINT(#BigBlindSeatId)
PRINT (#NextTurn)