I have a Stored Proc query below which involves returning partial delimited search string. E.g.searching passing a search string of ‘wis,k’ will return all results with ID that has ‘wis’ and ‘k’ in them. I am using a function and a cross join for this but the problem if attaching the cross join will prevent loading all my data which I will need to when I load this SPROC. I was thinking if a conditioned Cross Join is possible such that when my search string variable ‘@ReceiptNo’ is null then I will omit the Cross Join and allow all my data to be displayed. Please kindly advice. Thanks.
Portion of my SPROC:
FROM [Transact] T
LEFT JOIN [Outlet] O On (T.Outlet_Code = O.Code)
LEFT JOIN [SystemCode] SC on (CONVERT(NVARCHAR,T.Mode) = SC.Code)
CROSS JOIN DBO.SPLIT(@ReceiptNo , ',') --SPLIT function to seperate delimited string
Where
(
CardNo In
(
Select [CardNo]
FROM [Card]
WHERE [CardNo] = @CardNo
AND [DeletedBy] IS NULL
AND [DeletedOn] IS NULL
AND [MemberID] = @MemberId
)
)
and
(
(T.TransactDate Between @TransactDateFrom And @TransactDateTo
or @TransactDateFrom is null
or @TransactDateTo is null
)
and (T.TransactDate >= @TransactDateFrom
or @TransactDateFrom is null)
and (T.TransactDate <= @TransactDateTo
or @TransactDateTo is null)
and
(
(',' + @Mode +',' LIKE '%,' + CONVERT(VARCHAR, T.Mode) + ',%')
or @Mode is null
)
and (T.ReceiptNo LIKE '%' + VAL + '%') --This is the 'LIKE' condition to return desired search string results
or (@TransactDateFrom is null
and @TransactDateTo is null
and @Mode is null
and @Outlet_Code is null
and @ReceiptNo is null
)
)
Group by T.AutoID, TransactDate,TransactTime, SC.Name, O.Name
, ReceiptNo, AmountSpent, TransactPoints, VoidOn
You need to take care of NULL and set it to any constant value. Modify CROSS JOIN to (read notes below query):
In query above,
Portionis column returned byDBO.SPLITfunction. Change its name to appropriate and add more columns (withISNULL) if needed.Am I missing something or You can simply use LEFT JOIN instead of CROSS JOIN? Also, You might consider putting DBO.SPLIT function result into temporary table, index it and then use it in your CROSS/LEFT JOIN.
EDIT#1: I can’t find any reason why You should not change CROSS JOIN to LEFT JOIN, as it will process less rows when @RecepitNo is not NULL.