I faced strange problem.
Here is a PostgreSQL function:
CREATE FUNCTION public.search_companies_ordered(name character varying DEFAULT NULL::character varying, "categoryIds" integer[] DEFAULT NULL::integer[], "cityIds" integer[] DEFAULT NULL::integer[], departments public.department[] DEFAULT NULL::public.department[], "stockTemperatures" public.stock_temperature[] DEFAULT NULL::public.stock_temperature[], "order" public.search_companies_order DEFAULT 'createdAt'::public.search_companies_order, order_type public.order_type DEFAULT 'desc'::public.order_type) RETURNS SETOF public.company
LANGUAGE plpgsql STABLE
AS $$
begin
IF "search_companies_ordered"."order_type" = 'asc'::order_type THEN
return query
SELECT * FROM "search_companies"(
name := search_companies_ordered."name",
"categoryIds" := search_companies_ordered."categoryIds",
"cityIds" := search_companies_ordered."cityIds",
departments := search_companies_ordered.departments,
"stockTemperatures" := search_companies_ordered."stockTemperatures"
) AS c
ORDER BY (
CASE WHEN "search_companies_ordered"."order" = 'id'::search_companies_order THEN
c."id"
END,
CASE WHEN "search_companies_ordered"."order" = 'name'::search_companies_order THEN
c."name"
END,
CASE WHEN "search_companies_ordered"."order" = 'createdAt'::search_companies_order THEN
c."createdAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'updatedAt'::search_companies_order THEN
c."updatedAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'lastCommentAt'::search_companies_order THEN
c."lastCommentAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'commentsCount'::search_companies_order THEN
c."commentsCount"
END
) ASC NULLS LAST;
ELSE
return query
SELECT * FROM "search_companies"(
name := search_companies_ordered."name",
"categoryIds" := search_companies_ordered."categoryIds",
"cityIds" := search_companies_ordered."cityIds",
departments := search_companies_ordered.departments,
"stockTemperatures" := search_companies_ordered."stockTemperatures"
) AS c
ORDER BY (
CASE WHEN "search_companies_ordered"."order" = 'id'::search_companies_order THEN
c."id"
END,
CASE WHEN "search_companies_ordered"."order" = 'name'::search_companies_order THEN
c."name"
END,
CASE WHEN "search_companies_ordered"."order" = 'createdAt'::search_companies_order THEN
c."createdAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'updatedAt'::search_companies_order THEN
c."updatedAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'lastCommentAt'::search_companies_order THEN
c."lastCommentAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'commentsCount'::search_companies_order THEN
c."commentsCount"
END
) DESC NULLS LAST;
END IF;
return;
end;
$$;
Everything working fine, except NULLS LAST, that does't takes any effect on resulting records order.
I've tried to omit brackets in ORDER BY – no effect:
ORDER BY
CASE WHEN "search_companies_ordered"."order" = 'id'::search_companies_order THEN
c."id"
END,
CASE WHEN "search_companies_ordered"."order" = 'name'::search_companies_order THEN
c."name"
END,
CASE WHEN "search_companies_ordered"."order" = 'createdAt'::search_companies_order THEN
c."createdAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'updatedAt'::search_companies_order THEN
c."updatedAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'lastCommentAt'::search_companies_order THEN
c."lastCommentAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'commentsCount'::search_companies_order THEN
c."commentsCount"
END
ASC NULLS LAST;
search_companies function is following:
CREATE FUNCTION public.search_companies(name character varying DEFAULT NULL::character varying, "categoryIds" integer[] DEFAULT NULL::integer[], "cityIds" integer[] DEFAULT NULL::integer[], departments public.department[] DEFAULT NULL::public.department[], "stockTemperatures" public.stock_temperature[] DEFAULT NULL::public.stock_temperature[]) RETURNS SETOF public.company
LANGUAGE sql STABLE
AS $$
SELECT DISTINCT ON (c."id")
c.*
FROM
public.company AS c
LEFT JOIN
"companyCities" cC ON c.id = cC."companyId"
LEFT JOIN
"companyCategories" cCat ON c.id = cCat."companyId"
LEFT JOIN
"companyVisit" cv ON c.id = cv."companyId"
WHERE (
CASE WHEN "search_companies"."name" is not null THEN
c.name ILIKE "search_companies"."name"
ELSE true END
) AND (
CASE WHEN "search_companies"."cityIds" is not null THEN
"search_companies"."cityIds" #> array[cC."cityId"]
ELSE true END
) AND (
CASE WHEN "search_companies"."categoryIds" is not null THEN
"search_companies"."categoryIds" #> array[cCat."categoryId"]
ELSE true END
) AND (
CASE WHEN "search_companies"."departments" is not null THEN
"search_companies"."departments" #> array[cCat.department]
ELSE true END
) AND (
CASE WHEN "search_companies"."stockTemperatures" is not null THEN
c."stockTemperatures" && "search_companies"."stockTemperatures"
ELSE true END
)
ORDER BY c."id";
$$;
Function search_companies is working.
select id, name, "lastCommentAt" from search_companies() order by "lastCommentAt" desc nulls last limit 100;
Where the problem is?
You're ENDing the CASEs early which creates multiple cases and that doesn't work well with order by.
Instead of:
ORDER BY (
CASE WHEN "search_companies_ordered"."order" = 'id'::search_companies_order THEN
c."id"
END,
CASE WHEN "search_companies_ordered"."order" = 'name'::search_companies_order THEN
c."name"
END,
CASE WHEN "search_companies_ordered"."order" = 'createdAt'::search_companies_order THEN
c."createdAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'updatedAt'::search_companies_order THEN
c."updatedAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'lastCommentAt'::search_companies_order THEN
c."lastCommentAt"
END,
CASE WHEN "search_companies_ordered"."order" = 'commentsCount'::search_companies_order THEN
c."commentsCount"
END
) ASC NULLS LAST;
Try:
ORDER BY
CASE WHEN "search_companies_ordered"."order" = 'id'::search_companies_order THEN
c."id"
WHEN "search_companies_ordered"."order" = 'name'::search_companies_order THEN
c."name"
WHEN "search_companies_ordered"."order" = 'createdAt'::search_companies_order THEN
c."createdAt"
WHEN "search_companies_ordered"."order" = 'updatedAt'::search_companies_order THEN
c."updatedAt"
WHEN "search_companies_ordered"."order" = 'lastCommentAt'::search_companies_order THEN
c."lastCommentAt"
WHEN "search_companies_ordered"."order" = 'commentsCount'::search_companies_order THEN
c."commentsCount"
END
ASC NULLS LAST;
ASC/DESC and NULLS FIRST/NULLS LAST do not affect all (comma separated) expressions in the ORDER BY clause, only the one where they stand.
So
... ORDER BY a, b, c DESC NULLS LAST
is the same as
... ORDER BY a ASC NULLS LAST,
b ASC NULLS LAST,
c DESC NULLS LAST
If you want all expressions sorted descending with the NULLs in the end, you'll have to append DESC NULLS LAST to each of the ORDER BY expressions.
Related
SELECT
CASE WHEN a.text IS NOT NULL THEN a.text
WHEN a.number IS NOT NULL THEN a.number::text
WHEN a.id IS NOT NULL THEN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
ELSE NULL
END
FROM
table_one a
WHERE
a.roll = '20';
above query returns error as
ERROR: more than one row returned by a subquery used as an expression
Is there any way to handle the multiple rows returned from subquery. Expecting multiple resultset from THEN statement
SELECT
CASE WHEN a.text IS NOT NULL THEN a.text
WHEN a.number IS NOT NULL THEN a.number::text
WHEN a.id IS NOT NULL THEN a.id IN (Select b.text from table_two b
Join table_one a ON b.id = a.id where b.place = 'city' AND a.roll = '20' )
ELSE NULL
END
FROM
table_one a
WHERE
a.roll = '20';
If I try to handle multiple result using IN, then I get error
"ERROR: operator does not exist: integer = character varying
because a.id is integer and sub query returns string results
How can i achieve dynamic order by column and sort direction in a postgresql function.
Here is what i have so far:
CREATE OR REPLACE FUNCTION get_urls_by_crawl_id(
p_account_id character varying(64),
p_crawl_id character varying(64),
p_sort_column character varying(30),
p_sort_direction character varying(30),
p_page integer,
p_total integer
)
RETURNS TABLE(id character varying(64), source_url text, http_status_code integer, ref_cnt integer) AS $BODY$
BEGIN
RETURN QUERY SELECT u.id, u.source_url, u.http_status_code, u.ref_cnt FROM url AS u
JOIN crawl AS c ON(u.crawl_id = c.id)
JOIN site AS s ON(c.site_id = s.id)
JOIN person AS p ON(s.person_id = p.id)
WHERE p.account_id = p_account_id AND u.crawl_id = p_crawl_id AND u.secured = 0
ORDER BY p_sort_column (CASE WHEN p_sort_direction = 'ASC' THEN ASC ELSE DESC END) LIMIT p_total OFFSET (p_page * p_total);
END;
$BODY$ LANGUAGE plpgsql;
the psql client returns this error:
ERROR: syntax error at or near "ASC"
LINE 16: ...t_column (CASE WHEN p_sort_direction = 'ASC' THEN ASC ELSE D...
I have tried multiple forms of the CASE statement but none seems to work.
Use two different order by keys:
ORDER BY (case when p_sort_direction = 'ASC' then p_sort_column end)
asc,
p_sort_column desc
LIMIT p_total OFFSET (p_page * p_total);
Note that you have another problem. p_sort_column is a string. You would need to use dynamic SQL to insert it into the code.
Alternatively, you can use a series of cases:
order by (case when p_sort_column = 'column1' and p_sort_direction = 'ASC' then column1 end) asc,
(case when p_sort_column = 'column1' and p_sort_direction = 'DESC' then column1 end) desc,
(case when p_sort_column = 'column2' and p_sort_direction = 'ASC' then column2 end) asc,
(case when p_sort_column = 'column2' and p_sort_direction = 'DESC' then column2 end) desc,
. . .
I need to update 2 columns in table with same conditions. I know, that each of them would take a lot of time. How can I concatenate 2 updates into 1, which can be faster?
-- first update
update t1
set col1 =
case when cc1 is not NULL and cc1 <> 0 then 'A'
when cc2 is not NULL and cc2 <> 0 then 'B'
when cc3 is not NULL and cc3 <> 0 then 'C'
else null
end;
-- with same cond
update t1
set col2 =
case when cc1 is not NULL and cc1 <> 0 then 'qwe rty'
when cc2 is not NULL and cc2 <> 0 then 'qzaz wsx'
when cc3 is not NULL and cc3 <> 0 then 'zxcv asdf'
else 'pl ok'
end;
-- my effort to concatenate, dont work
update t1
set (col1, col2) =
(select c1, c2 from
(select case when t2.cc1 is not NULL and t2.cc1 <> 0 then 'A' as c1, 'qwe rty' as c2
when t2.cc2 is not NULL and t2.cc2 <> 0 then ('B', 'qaz wsx')
when t2.cc3 is not NULL and t2.cc3 <> 0 then ('C', ' zxcv asdf')
else (null, 'pl ok')
end
from t1 as t2 where t1.key_column1 = t2.key_column1 and t1.key_column2 = t2.key_column2 and t1.key_column3 = t2.key_column3) f)
;
This is the way I would do it.
WITH cte AS (SELECT * FROM
(VALUES(1, 'A', 'qwe rty'),(2, 'B', 'qaz wsx'),(3, 'C', 'zxcv asdf'),(4, NULL, 'pl ok')) v (id,c1,c2))
UPDATE so_demo
SET col1 = cte.c1, col2 = cte.c2
FROM cte WHERE cte.id = CASE WHEN COALESCE(cc1, 0) <> 0 THEN 1
WHEN COALESCE(cc2, 0) <> 0 THEN 2
WHEN COALESCE(cc3, 0) <> 0 THEN 3
ELSE 4 END;
By way of explanation, I have put the possible values into a cte assigning them an id in addition to the values. I can then put the case statement in the where clause generating the necessary id. Note the use of COALESCE to make the WHENs simpler to read.
One way is to use arrays.
UPDATE t1
SET (col1,
col2) = (SELECT x[1],
x[2]
FROM (SELECT CASE
WHEN cc1 IS NOT NULL
AND cc1 <> 0 THEN
ARRAY['A',
'qwe rty']
WHEN cc2 IS NOT NULL
AND cc2 <> 0 THEN
ARRAY['B',
'qzaz wsx']
...
ELSE
ARRAY[NULL,
'pl ok']
END) AS x
(x));
But in terms of runtime optimization the gain compared to just UPDATE ... SET col1 = CASE ..., col2 = CASE ... should be neglectable, if any.
I have two tables with identical columns, in an identical order. I have a desire to join across one of the two tables, depending on a subquery condition. For example, assume I have the following schema:
CREATE TABLE b (
bid SERIAL PRIMARY KEY,
cid INT NOT NULL
);
CREATE TABLE a1 (
aid SERIAL PRIMARY KEY,
bid INT NOT NULL REFERENCES b
);
CREATE TABLE a2 (
aid SERIAL PRIMARY KEY,
bid INT NOT NULL REFERENCES b
);
I would like a query, that performs a join across either a1 or a2 based on some condition. Something like:
WITH z AS (
SELECT cid, someCondition FROM someTable
)
SELECT *
FROM CASE z.someCondition THEN a1 ELSE a2 END
JOIN b USING (bid)
WHERE cid = (SELECT cid FROM z);
However, the above doesn't work. Is there some way to conditionally join across a1 or a2, depending on some boolean condition stored in table z?
If the conditions are exclusive (I expect they are): just do both queries and UNION ALL them, with the smart union construct:
WITH z AS (
SELECT cid
, (cid %3) AS some_condition -- Fake ...
FROM b
)
SELECT *
FROM a1
JOIN b USING (bid)
WHERE EXISTS( SELECT * FROM z
WHERE some_condition = 1 AND cid = b.cid )
UNION ALL
SELECT *
FROM a2
JOIN b USING (bid)
WHERE EXISTS( SELECT * FROM z
WHERE some_condition = 2 AND cid = b.cid )
;
A somewhat different syntax to do the same:
WITH z AS (
SELECT cid
, (cid %3) AS some_condition
FROM b
)
SELECT *
FROM a1
JOIN b ON a1.bid = b.bid
AND EXISTS( SELECT * FROM z
WHERE some_condition = 1 AND cid = b.cid )
UNION ALL
SELECT *
FROM a2
JOIN b ON a2.bid = b.bid
AND EXISTS( SELECT * FROM z
WHERE some_condition = 2 AND cid = b.cid )
;
SQL syntax does not allow conditional joins.
Probably the simplest way to achieve a similar effect is to use a dynamic query in a plpgsql function, which may look like this:
create function conditional_select(acid int, some_condition boolean)
returns table (aid int, bid int, cid int)
language plpgsql as $$
declare
tname text;
begin
if some_condition then tname = 'a1';
else tname = 'a2';
end if;
return query execute format ($fmt$
select a.aid, b.bid, b.cid
from %s a
join b using(bid)
where cid = %s;
$fmt$, tname, acid);
end $$;
select * from conditional_select(1, true)
If, like in your example, you have only a few columns that you want to output, you can use the CASE statement for every column:
SELECT CASE z.someCondition THEN a1.aid ELSE a2.aid END AS aid,
CASE z.someCondition THEN a1.bid ELSE a2.bid END AS bid
FROM b
JOIN a1 ON a1.bid = b.bid
JOIN a2 ON a2.bid = b.bid
JOIN someTable z USING (cid);
Depending on the size of tables a1 and a2 and how many columns you have to output, this may or my not be faster than Klin's solution with a function, which is inherently slower than plain SQL and even more so because of the dynamic query. Given that z.someCondition is a boolean value already, the CASE evaluation will be very fast. Small tables + few columns = this solution; large tables + many columns = Klin's solution.
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.)