I’ve created the following stored procedure:
ALTER PROCEDURE [dbo].[ExampleSP]
(
@SearchText NVARCHAR(4000),
@ID INT = NULL
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
deID,
deTitle
FROM tblDemo As de
LEFT JOIN tblLinkTable As lnk ON (lnk.ID = de.deID)
WHERE CONTAINS(cstKeywords, @SearchText)
AND ((@ID IS NULL) OR (lnk.ID = @ID))
GROUP BY deID,Title
ORDER BY de.Title
But I also need to be able to find the first field that is not null out of the following table columns:
deIntroText, deCompanyText, deTimetableText and deExampleText
And i need to do this for each record that is returned from the SELECT.
So I realise that i’d need to create a temporary column to store it in and i guess you’d need to use an IF statement like this:
IF deIntroText IS NOT Null
THEN TempFieldToReturn = 1
ELSE IF deCompanyText IS NOT Null
THEN TempFieldToReturn = 2
ELSE IF deTimetableText IS NOT Null
THEN TempFieldToReturn = 3
ELSE IF deExampleText IS NOT Null
THEN TempFieldToReturn = 4
So my question is – what is the best way to achieve this? Any examples would be appreciated.
No real shortcut – just use a
CASEexpression:This is a Searched
CASE– there are actually two variants ofCASE. I guessed at 5 if all of the columns areNULL– you might leave off theELSE 5portion, if you want aNULLresult in such a case.