SQL Statement with IN CASE - select

SELECT user
FROM userlist zH with(nolock)
where zH.user in (case when zh.trait='1' then ('B', 'HO', 'KO', 'PL','APP','2A','2B') else ('O') end)
can this statement with the where-in-case work? i hope you get what i meant. thanks.

You can use nested case statement, like
SELECT user
FROM userlist zH with(nolock)
where 'true' =
(case when zh.trait = '1'
then
case when zH.user in ('B', 'HO', 'KO', 'PL','APP','2A','2B')
then 'true'
else 'false'
end
else
case when zH.user = 'O'
then 'true'
else 'false'
end
end)

SELECT [user]
FROM userlist zH WITH ( NOLOCK )
WHERE ( zh.trait = '1'
AND zH.[user] IN ( 'B', 'HO', 'KO', 'PL', 'APP', '2A', '2B' )
)
OR ( zh.trait <> '1'
AND zH.[user] IN ( 'O' )
)

Related

Postgres CASE expression then null

The below query is part of a select query which I have got in my application
where
case when o.tracking_id <> '0' then a.account_id is null
and
o.status = 'N'
else
(
o.tracking_id = '0'
and
o.status = 'N'
)
END
I am having hardtime to understand the below line
Can you please tell me what does this exactly mean ?
case when o.tracking_id <> '0' then a.account_id is null
I wouldn't use a CASE expression here but instead would use the following logic:
WHERE
(o.tracking_id <> '0' AND a.account_id IS NULL AND o.status = 'N')
OR
(o.tracking_id = '0' AND o.status = 'N')
The condition is written somewhat clumsily. It is equivalent to this more readable expression:
where (o.tracking_id = '0' or a.account is null)
and o.status = 'N';

DB2 Replacing string using CASE When

My problem is that I concatenate the values ​​of column col2 but in the When I have to replace them with the values ​​in Then. For some reason my code doesn't work when I put this code inside my query, is there another way to do it? Would using Replace be good in this case? Could you give an example?
So my code is this one:
cte(col1, AliasCol) as
(Select col1,
CASE
WHEN Replace(Replace( LISTAGG(DISTINCT CONCAT( ', ', col2)) WITHIN GROUP
(ORDER BY CONCAT( ', ',col2)),',',''),' ','') = 'A' THEN 'Z'
WHEN Replace(Replace( LISTAGG(DISTINCT CONCAT( ', ', col2)) WITHIN GROUP
(ORDER BY CONCAT( ', ', col2)),',',''),' ','') = 'B' THEN 'Y'
WHEN Replace(Replace( LISTAGG(DISTINCT CONCAT( ', ', col2)) WITHIN GROUP
(ORDER BY CONCAT( ', ', col2)),',',''),' ','') = 'C' THEN 'X'
END
FROM Table
Where
col2 IN ('A','B','C','D')
and col >= (select TodaysDate from Date)
GROUP By col1
)
My output should be: ZYXD
Edit:
My col2 column displays all codes like this:
A
B
C
D
After I concat them to this ABCD the value of ABCD should be replace by ZYXD. Replacing 'A' by 'Z', 'Y' by 'B' and 'C' by X'.
Try this:
WITH MYTAB(COL1, COL2) AS
(
VALUES
(1, 'A')
, (1, 'A')
, (1, 'B')
, (1, 'C')
, (1, 'D')
)
SELECT
COL1
, TRANSLATE(LISTAGG(DISTINCT COL2) WITHIN GROUP (ORDER BY COL2), 'ZYX', 'ABC') MY_OUT
FROM MYTAB
GROUP BY COL1;

My stored procedure text search is buggy

I'm stuck - I have this nice little text searcher I've put together.
I realised I needed to count lnies in individual blocks of text that the stored procedure is stored in, so I think I've figured a way to do that.
But it's not getting every instance of a search term in a stored procedure - and I think it's the same reason... the search term is split across a text boundary.
I've looked at how to change my query - and I'm coming up blank. The skills involved to change it are beyond me!
--Text searcher.
DECLARE #searchString VARCHAR(255),
#doesNotContain VARCHAR(255),
#previewLength INTEGER,
#findStoredProcedures VARCHAR(3),
#findTableFunction VARCHAR(3),
#findScalerFunction VARCHAR(3),
#findTrigger VARCHAR(3),
#findView VARCHAR(3),
#findUserTable VARCHAR(3),
#onlyInName VARCHAR(3)
--------------------------------------------------------
-- Search criteria:
SET #searchString = 'My search Term'
SET #findStoredProcedures = 'yes'
SET #findTableFunction = 'yes'
SET #findScalerFunction = 'yes'
SET #findUserTable = 'yes'
SET #findTrigger = 'yes'
SET #findView = 'yes'
SET #doesNotContain = ''
SET #previewLength = 30
--------------------------------------------------------
SELECT DISTINCT
ISNULL(
(SELECT REPLACE(CONVERT(VARCHAR(20), (CAST(SUM(LEN(SC2.text)) AS MONEY)), 1), '.00', '')
FROM syscomments SC2 WHERE SC2.id = SO.id GROUP BY SC2.id)
, '')
AS [Object length]
,
SO.name AS [Object name]
,
CASE
WHEN SO.xtype = 'P' THEN 'Stored Procedure'
WHEN SO.xtype = 'TF' THEN 'Table Function'
WHEN SO.xtype = 'FN' THEN 'Scaler Function'
WHEN SO.xtype = 'U' THEN 'User Table'
WHEN SO.xtype = 'TR' THEN 'Trigger'
WHEN SO.xtype = 'V' THEN 'View'
END
+ ISNULL((SELECT ' - ' + name FROM sysobjects WHERE id = SO.parent_obj), '')
AS [Object type]
,
ISNULL(SUBSTRING(SC.text, CHARINDEX(#searchString, SC.text) - #previewLength, #previewLength) +
SUBSTRING(SC.text, CHARINDEX(#searchString, SC.text), #previewLength + LEN(#searchString))
, '') AS [Preview of code]
,
(SELECT
COALESCE(
SUM(LEN(SC3.text) - LEN(REPLACE(SC3.text, CHAR(13), '')) + 1) + 4
+
(
SELECT
(LEN(LEFT(SC4.text, CHARINDEX(#searchString, SC4.text))) -
LEN(REPLACE(LEFT(SC4.text, CHARINDEX(#searchString, SC4.text)), CHAR(13), '')))
FROM syscomments SC4
WHERE
SC4.id = SO.id
AND SC4.colid = SC.colid
)
,
SUM(LEN(SC3.text) - LEN(REPLACE(SC3.text, CHAR(13), '')) + 1) + 4
,
(
SELECT
(LEN(LEFT(SC4.text, CHARINDEX(#searchString, SC4.text))) -
LEN(REPLACE(LEFT(SC4.text, CHARINDEX(#searchString, SC4.text)), CHAR(13), '')) + 1)
FROM syscomments SC4
WHERE
SC4.id = SO.id
AND SC4.colid = SC.colid
)
)
FROM syscomments SC3
WHERE
SC3.id = SO.id
AND SC3.colid < SC.colid
)
AS [Line number]
FROM sysobjects SO
LEFT JOIN syscomments SC
ON SO.id = SC.id
WHERE
(
(SO.type = 'P' AND #findStoredProcedures = 'yes')
OR
(SO.type = 'TF' AND #findTableFunction = 'yes')
OR
(SO.type = 'FN' AND #findScalerFunction = 'yes')
OR
(SO.type = 'TR' AND #findTrigger = 'yes')
OR
(SO.type = 'U' AND #findUserTable = 'yes')
OR
(SO.type = 'V' AND #findView = 'yes')
)
AND SO.category = 0
AND
(
(CHARINDEX(#searchString, SC.text) > 0
AND CHARINDEX(#doesNotContain, SC.text) = 0)
OR
(SO.type = 'U'
AND CHARINDEX(#searchString, SO.name) > 0
AND CHARINDEX(#doesNotContain, SO.name) = 0)
)
ORDER BY
[Object type], [Object name], [Line number]
Your where clause seems to have an issue, this bit here
(
(CHARINDEX(#searchString, SC.text) > 0
AND CHARINDEX(#doesNotContain, SC.text) = 0)
--OR
--(SO.type = 'U'
--AND CHARINDEX(#searchString, SO.name) > 0
--AND CHARINDEX(#doesNotContain, SO.name) = 0)

Parse Prefix First Middle Last Suffix from full name

I need to parse a full name in the format, prefix first middle last suffix, but not all parts may be included. I have the prefix first middle and last working, but Jr gets stuffed in with the last name. How do I get the suffix to come out in a suffix column? Example includes data.
SELECT
FIRST_NAME.INPUT_DATA
,FIRST_NAME.PREFIX
,FIRST_NAME.FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REMAINING)
THEN NULL --no more spaces found, consider remaining to be last name
ELSE SUBSTRING(
FIRST_NAME.REMAINING
,1
,CHARINDEX(' ',FIRST_NAME.REMAINING)-1
)
END AS MIDDLE_NAME
,SUBSTRING(
FIRST_NAME.REMAINING
,1 + CHARINDEX(' ',FIRST_NAME.REMAINING)
,LEN(FIRST_NAME.REMAINING)
) AS LAST_NAME
FROM
(
SELECT
PREFIX.PREFIX
,CASE WHEN 0 = CHARINDEX(' ',PREFIX.REMAINING)
THEN PREFIX.REMAINING --no space found, return the entire string
ELSE SUBSTRING(
PREFIX.REMAINING
,1
,CHARINDEX(' ',PREFIX.REMAINING)-1
)
END AS FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',PREFIX.REMAINING)
THEN NULL --no spaces found, consider to be first name
ELSE SUBSTRING(
PREFIX.REMAINING
,CHARINDEX(' ',PREFIX.REMAINING)+1
,LEN(PREFIX.REMAINING)
)
END AS REMAINING
,PREFIX.INPUT_DATA
FROM
(
SELECT --CLEAN_DATA
--if first three characters match list,
--parse as a "PREFIX". else return NULL for PREFIX.
CASE WHEN SUBSTRING(CLEAN_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(CLEAN_DATA.FULL_NAME,1,3)))
ELSE NULL
END AS PREFIX
,CASE WHEN SUBSTRING(CLEAN_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(CLEAN_DATA.FULL_NAME,4,LEN(CLEAN_DATA.FULL_NAME))))
ELSE LTRIM(RTRIM(CLEAN_DATA.FULL_NAME))
END AS REMAINING
,CLEAN_DATA.INPUT_DATA
FROM
(
SELECT
--trim leading & trailing spaces to prepare for processing
--replace extra spaces in name
REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME
,FULL_NAME AS INPUT_DATA
FROM
(
--test with test data, or table
--table
--SELECT CONTACT AS FULL_NAME
--FROM CONTACT
--test data
--/*
SELECT 'Andy D Where' AS FULL_NAME
UNION SELECT 'Cathy T Landers' AS FULL_NAME
UNION SELECT 'Ms Annie Wint There' AS FULL_NAME
UNION SELECT 'Frank Fields' AS FULL_NAME
UNION SELECT 'Howdy U Pokes Jr.' AS FULL_NAME
--*/
) SOURCE_DATA
) CLEAN_DATA
) PREFIX
) FIRST_NAME
--credits to JStyons of course
Hope this helps. I have only added Generational SUFFIX titles(Sr, Jr), If more are needed you could add to the Case statement as needed. I am also assuming that your Db is case insensitive.
Assumption (Business Rules):
First Name has no spaces
Middle Name has no spaces
Last name has no spaces
Prefix's are only of the form 'MR ','MS ','DR ','MRS' with no period "."
Suffix's are only of the form 'Sr', 'Jr', 'Sr.', 'Jr.'
The Database is case insensitive
IF OBJECT_ID('tempdb..#cte_SpaceFix') IS NOT NULL
DROP TABLE #cte_SpaceFix
;WITH cte_OriginalData (FullName)
AS (
SELECT 'Andy D Where'
UNION
SELECT 'Cathy T Landers'
UNION
SELECT 'Ms Annie Wint There'
UNION
SELECT 'Ms Annie Wint There Jr'
UNION
SELECT 'Mrs Annie There Jr'
UNION
SELECT 'Frank Fields'
UNION
SELECT 'Howdy U Pokes Jr.'
UNION
SELECT 'Howdy U Pokes Sr.'
UNION
SELECT 'Cathy T Landers Jr'
UNION
SELECT 'Landers Jr'
)
,cte_FullNameRemoveTail AS
(
SELECT LTRIM(RTRIM(FullName)) AS FullName
FROM cte_OriginalData
)
,cte_Parse_Prefix(Prefix,FullFirst_Prefix,FullName) AS
(
SELECT CASE
WHEN SUBSTRING(FullName, 1, 3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(FullName, 1, 3)))
ELSE NULL
END AS Prefix,
CASE
WHEN SUBSTRING(FullName, 1, 3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(FullName, 4, 8000)))
ELSE LTRIM(RTRIM(FullName))
END AS FullFirst_Prefix,
FullName
FROM cte_FullNameRemoveTail
)
,cte_Parse_Suffix(Prefix,FullFirst_Prefix_Suffix,Suffix,FullName) AS
(
SELECT Prefix,
CASE
WHEN RIGHT(FullFirst_Prefix,3) = ' JR' THEN LTRIM(RTRIM(SUBSTRING(FullFirst_Prefix,1,LEN(FullFirst_Prefix)-3)))
WHEN RIGHT(FullFirst_Prefix,4) = ' JR.' THEN LTRIM(RTRIM(SUBSTRING(FullFirst_Prefix,1,LEN(FullFirst_Prefix)-4)))
WHEN RIGHT(FullFirst_Prefix,3) = ' SR' THEN LTRIM(RTRIM(SUBSTRING(FullFirst_Prefix,1,LEN(FullFirst_Prefix)-3)))
WHEN RIGHT(FullFirst_Prefix,4) = ' SR.' THEN LTRIM(RTRIM(SUBSTRING(FullFirst_Prefix,1,LEN(FullFirst_Prefix)-4)))
ELSE LTRIM(RTRIM(FullFirst_Prefix))
END AS FullFirst_Prefix_Suffix,
CASE
WHEN RIGHT(FullFirst_Prefix,3) = ' JR'
OR RIGHT(FullFirst_Prefix,4) = ' JR.'
THEN 'Jr'
WHEN RIGHT(FullFirst_Prefix,3) = ' SR'
OR RIGHT(FullFirst_Prefix,4) = ' SR.'
THEN 'Sr'
ELSE NULL
END AS Suffix,
FullName
FROM cte_Parse_Prefix
)
,cte_SpaceFix(Prefix, FullFirst_Prefix_Suffix, Suffix, FullName) AS
(
SELECT Prefix,
CASE
WHEN LEN(FullFirst_Prefix_Suffix) - LEN(REPLACE(FullFirst_Prefix_Suffix, ' ', '')) > 2 THEN REPLACE(REPLACE(REPLACE(REPLACE(FullFirst_Prefix_Suffix,SPACE(5), SPACE(1)),SPACE(4), SPACE(1)),SPACE(3), SPACE(1)),SPACE(2), SPACE(1))
ELSE FullFirst_Prefix_Suffix
END AS FullFirst_Prefix_Suffix,
Suffix,
FullName
FROM cte_Parse_Suffix
)
SELECT * INTO #cte_SpaceFix
FROM cte_SpaceFix
;WITH cte_Parse_FirstName(Prefix, FirstName, Suffix, FullFirst_Prefix_Suffix_FirstName, FullName) AS
(
SELECT Prefix,
CASE
WHEN FullFirst_Prefix_Suffix IS NULL THEN NULL
WHEN LEN(FullFirst_Prefix_Suffix) - LEN(REPLACE(FullFirst_Prefix_Suffix, ' ', '')) >= 1 THEN LEFT(FullFirst_Prefix_Suffix,CHARINDEX(' ',FullFirst_Prefix_Suffix))
WHEN LEN(FullFirst_Prefix_Suffix) - LEN(REPLACE(FullFirst_Prefix_Suffix, ' ', '')) = 0 THEN FullFirst_Prefix_Suffix
ELSE NULL
END AS FirstName,
Suffix,
CASE
WHEN FullFirst_Prefix_Suffix IS NULL THEN NULL
WHEN LEN(FullFirst_Prefix_Suffix) - LEN(REPLACE(FullFirst_Prefix_Suffix, ' ', '')) >= 1 THEN LTRIM(RTRIM(REPLACE(FullFirst_Prefix_Suffix,LEFT(FullFirst_Prefix_Suffix,CHARINDEX(' ',FullFirst_Prefix_Suffix)),'')))
WHEN LEN(FullFirst_Prefix_Suffix) - LEN(REPLACE(FullFirst_Prefix_Suffix, ' ', '')) = 0 THEN NULL
ELSE NULL
END AS FullFirst_Prefix_Suffix_FirstName,
FullName
FROM #cte_SpaceFix
)
,cte_Parse_LastName(Prefix, FirstName, LastName, Suffix, MiddleName, FullName) AS
(
SELECT Prefix,
FirstName,
CASE
WHEN FullFirst_Prefix_Suffix_FirstName IS NULL THEN NULL
WHEN LEN(FullFirst_Prefix_Suffix_FirstName) - LEN(REPLACE(FullFirst_Prefix_Suffix_FirstName, ' ', '')) >= 1 THEN SUBSTRING(FullFirst_Prefix_Suffix_FirstName,CHARINDEX(' ',FullFirst_Prefix_Suffix_FirstName)+1,8000)
WHEN LEN(FullFirst_Prefix_Suffix_FirstName) - LEN(REPLACE(FullFirst_Prefix_Suffix_FirstName, ' ', '')) = 0 THEN FullFirst_Prefix_Suffix_FirstName
ELSE NULL
END AS LastName,
Suffix,
CASE
WHEN FullFirst_Prefix_Suffix_FirstName IS NULL THEN NULL
WHEN LEN(FullFirst_Prefix_Suffix_FirstName) - LEN(REPLACE(FullFirst_Prefix_Suffix_FirstName, ' ', '')) >= 1 THEN LEFT(FullFirst_Prefix_Suffix_FirstName,CHARINDEX(' ',FullFirst_Prefix_Suffix_FirstName))
ELSE NULL
END AS MiddleName,
FullName
FROM cte_Parse_FirstName
)
SELECT Prefix, FirstName, MiddleName, LastName, Suffix--, FullName
FROM cte_Parse_LastName
IF OBJECT_ID('tempdb..#cte_SpaceFix') IS NOT NULL
DROP TABLE #cte_SpaceFix

T-SQL Paging Sorting & Filtering - Filtering not Working

T-SQL Paging Sorting & Filtering
I have been working on a T-SQL stored procedure for a number of hours now that will enable me to retrieve a paged set of articles that are sorted in ASC or DESC order based on a specified column.
I am now working on getting the stored procedure to filter based on the first character of the 'Title' field and have added the lines:
#StartAlpha nvarchar(1) = null
and
WHERE ((#StartAlpha IS NULL) OR (Title Like #StartAlpha + '%'))
see below.
The stored procedure no longer returns any results. And I don't really know why.
Can anyone please help?
Regards
Walter
USE [ABC]
GO
/****** Object: StoredProcedure [dbo].[Get_MyArticles_Paged] Script Date: 08/07/2011 20:41:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Get_MyArticles_Paged]
/*Paging Total For Output*/
#Row_Count BIGINT OUT,
/*Paging Inputs*/
#Page_Size INT = 10,
#Page_Number INT = 1,
#Sort_Column VARCHAR(100), /* ('articleid','createdate','title','subject') */
#Sort_Direction VARCHAR(4), /* ('ASC','DESC') */
#StartAlpha nvarchar(1) = null
AS
BEGIN
print #StartAlpha
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
/*========================================================================
Declare local variables
========================================================================*/
DECLARE #FirstRecord int
DECLARE #LastRecord int
-- create a temporary space for paged result set
DECLARE #PagedResults AS TABLE (
[ArticleID] INT,
[CreateDate] SMALLDATETIME,
[Title] VARCHAR(200),
[Subject] VARCHAR(500),
[Row_Number] BIGINT,
[Row_Count] BIGINT
);
/*========================
Normalize Paging Parameters
==========================*/
--Fix invalid input for Page Size
SET #Page_Size = CASE
WHEN #Page_Size IS NULL THEN 10
WHEN #Page_Size < 1 THEN 10
ELSE #Page_Size
END;
--Fix invalid input for Page Number
SET #Page_Number = CASE
WHEN #Page_Number IS NULL THEN 1
WHEN #Page_Number < 1 THEN 1
ELSE #Page_Number
END;
--starting record to use.
SET #FirstRecord = ((#Page_Number - 1) * #Page_Size) + 1
--last record to use.
SET #LastRecord = #FirstRecord + #Page_Size - 1
--ensure sort column is valid in the list
SET #Sort_Column = CASE
WHEN LOWER(#Sort_Column) IN ('articleid','createdate','title','subject')
THEN LOWER(#Sort_Column)
ELSE
'title' --default
END
--ensure sort direction is ASC or DESC
SET #Sort_Direction = CASE
WHEN LEFT(UPPER(COALESCE(#Sort_Direction, '')) + ' ', 4) = 'DESC'
THEN 'DESC' --explicit descending
WHEN #Sort_Column = 'created' AND LEFT(UPPER(COALESCE(#Sort_Direction,'')) + ' ', 3) <> 'ASC' THEN
'DESC' --default for created date
ELSE 'ASC' --default otherwise
END;
/*============
Prepare Results
==============*/
WITH [MyTempArea] AS (
SELECT TOP (#LastRecord)
[ArticleID],
[CreateDate],
[Title],
[Subject],
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='articleid' THEN [articleid] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='createdate' THEN [createdate] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='title' THEN [title] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='subject' THEN [subject] END END ASC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='articleid' THEN [articleid] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='createdate' THEN [createdate] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='title' THEN [title] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='subject' THEN [subject] END END DESC
) AS [Row_Number],
COUNT(*) OVER () AS [Row_Count]
FROM Articles
WHERE ((#StartAlpha IS NULL) OR (Title Like #StartAlpha + '%'))
)
INSERT INTO #PagedResults
SELECT * FROM [MyTempArea] WHERE [Row_Number] >= #FirstRecord;
/*===========
Return Results
=============*/
-- #Row_Count output param
SELECT #Row_Count = COALESCE(MAX(Row_Count), 0) FROM #PagedResults;
-- Paged results set to return
SELECT [ArticleID],[CreateDate],[Title],[Subject]
FROM #PagedResults
ORDER BY [Row_Number];
END
Thanks to everyone that made helpful suggestions.
I completely refactored the stored procedure and it now works. See below.
I'm not entirely sure why the original Stored Procedure didn't work and why this version does, but I thought I would share with the forum.
Thanks again.
Walter.
ALTER PROCEDURE [dbo].[Account_ContactGetData]
#CurrentPage int = null,
#PageSize int = null,
#SortColumn nvarchar(max) = null,
#SortDirection varchar(5),
#StartAlpha nvarchar(1) = null
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FirstRecord int;
DECLARE #LastRecord int;
--starting record to use.
SET #FirstRecord = ((#CurrentPage - 1) * #PageSize) + 1;
--last record to use.
SET #LastRecord = #FirstRecord + #PageSize - 1;
with ContactCTE as
(
SELECT [ContactID], [DisplayName], [FirstName], [MiddleName], [LastName],
(ROW_NUMBER() OVER (Order By
CASE WHEN #SortColumn='ContactID' AND #SortDirection='DESC' THEN ContactID END DESC,
CASE WHEN #SortColumn='ContactID' AND #SortDirection='ASC' THEN ContactID END ASC,
CASE WHEN #SortColumn='DisplayName' AND #SortDirection='DESC' THEN DisplayName END DESC,
CASE WHEN #SortColumn='DisplayName' AND #SortDirection='ASC' THEN DisplayName END ASC,
CASE WHEN #SortColumn='FirstName' AND #SortDirection='DESC' THEN FirstName END DESC,
CASE WHEN #SortColumn='FirstName' AND #SortDirection='ASC' THEN FirstName END ASC,
CASE WHEN #SortColumn='MiddleName' AND #SortDirection='DESC' THEN MiddleName END DESC,
CASE WHEN #SortColumn='MiddleName' AND #SortDirection='ASC' THEN MiddleName END ASC,
CASE WHEN #SortColumn='LastName' AND #SortDirection='DESC' THEN LastName END DESC,
CASE WHEN #SortColumn='LastName' AND #SortDirection='ASC' THEN LastName END ASC
)) AS Row
FROM Contact
WHERE
((#StartAlpha is NULL) OR (LastName Like #StartAlpha+ '%'))
)
SELECT [ContactID], [DisplayName], [FirstName], [MiddleName], [LastName]
FROM ContactCTE
WHERE Row BETWEEN #FirstRecord AND #LastRecord
END
Based on those requirements alone, this is what I would do:
WHERE ((#StartAlpha IS NULL) OR (LEFT(Title, 1) = #StartAlpha))
What do you get when you run just this part? (Please also state which values you are using in your parameters)
WITH [MyTempArea] AS (
SELECT TOP (#LastRecord)
[ArticleID],
[CreateDate],
[Title],
[Subject],
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='articleid' THEN [articleid] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='createdate' THEN [createdate] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='title' THEN [title] END END ASC,
CASE WHEN(#Sort_Direction = 'ASC') THEN CASE WHEN #Sort_Column='subject' THEN [subject] END END ASC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='articleid' THEN [articleid] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='createdate' THEN [createdate] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='title' THEN [title] END END DESC,
CASE WHEN(#Sort_Direction = 'DESC') THEN CASE WHEN #Sort_Column='subject' THEN [subject] END END DESC
) AS [Row_Number],
COUNT(*) OVER () AS [Row_Count]
FROM Articles
WHERE ((#StartAlpha IS NULL) OR (Title Like #StartAlpha + '%'))
)
SELECT * FROM [MyTempArea]
#Andreas LEFT(Title, 1) syntax would perform better than the like comparison... but using the like, this should work:
WHERE (Title Like isnull(#StartAlpha, '') + '%')
(The combination of working with nulls that OR makes me edgy.)