I am trying to select rows into a temporary table with a CASE statement in the ORDER BY clause but records are not being sorted on insert.
Declare #orderby varchar(10) , #direction varchar(10)
set #orderby = 'col1'
set #direction = 'desc'
select identity (int) as autoid, *
into #temp
from table
order by case when #direction = 'desc' and #orderby = 'co1' then col1 end desc
declare #startrow int
declare #maxrows int
set #starrow = 19
set #maxrow = 30
set rowcount #maxrows
select * from #temp
where autoid > #startrow
Worst case - you'll just have to use two separate SQL queries to achieve your goal:
if #direction = 'desc'
select identity (int) as autoid, *
into #temp
from table
order by col1 desc
if #direction = 'asc'
select identity (int) as autoid, *
into #temp
from table
order by col1 asc
You'll need to use multiple sort conditions in your order by clause to handle this properly. The problem with this approach is that the performance will be bad when you have a lot of rows in the table because of that nasty sort operation.
Instead, you may be better off using dynamic SQL (as someone else suggested).
Declare #orderby varchar(100) , #direction varchar(10)
set #orderby = 'col1'
set #direction = 'desc'
select identity (int) as autoid, *
into #temp
from table
order by case when #direction = 'desc' and #orderby = 'col1' then col1 end desc,
case when #direction = 'asc' and #orderby = 'col1' then col1 end,
case when #direction = 'desc' and #orderby = 'col2' then col2 end desc,
case when #direction = 'asc' and #orderby = 'col2' then col2 end,
case when #direction = 'desc' and #orderby = 'col3' then col3 end desc,
case when #direction = 'asc' and #orderby = 'col3' then col3 end,
case when #direction = 'desc' and #orderby = 'col4' then col4 end desc,
case when #direction = 'asc' and #orderby = 'col4' then col4 end,
case when #direction = 'desc' and #orderby = 'col5' then col5 end desc,
case when #direction = 'asc' and #orderby = 'col5' then col5 end
You can achieve this not using #temp tables insted use normal table temp. Later when you are done with your process you can drop it at the end.
declare #dir varchar(10)='desc'
DECLARE #str varchar(1000)
SET #str='select identity (int) as autoid,
* into temp from cust1 order by TransactionType '+#dir
exec(#str)
select * from temp
Related
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,
. . .
This is a T-SQL related question. I am using SQL Server 2012.
I have a table like this:
I would like to have output like this:
Explanation:
For each employee, there will be a row. An employee has one or more assignments. Batch Id specifies this. Based on the batch Id, the column names will change (e.g. Country 1, Country 2 etc.).
Approach so far:
Un-pivot the source table like the following:
select
EmpId, 'Country ' + cast(BatchId as varchar) as [ColumnName],
Country as [ColumnValue]
from
SourceTable
UNION
select
EmpId, 'Pass ' + cast(BatchId as varchar) as [ColumnName],
Pass as [ColumnValue]
from
SourceTable
which gives each column's values as rows. Then, this result can be pivoted to get the desired output.
Questions:
Is there a better way of doing this?
At the moment, I know there will be fixed amount of batches, but, for future, if I like to make the pivoting part dynamic, what is the best approach?
Using tools like SSIS or SSRS, is it easier to handle the pivot dynamically?
Screw doing it in SQL.
Let SSRS do the work for you with a MATRIX. It will PIVOT for you without having to create dynamic SQL to handle the terrible limitation of needing to know all the columns.
For your data, you would have EMP ID as the ROW Group and PASS as your column grouping.
https://msdn.microsoft.com/en-us/library/dd207149.aspx
There are many possible solutions to achieve what you want (search for Dynamic Pivot on multiple columns)
SqlFiddleDemo
Warning: I assume that columns Country and Pass are NOT NULL
CREATE TABLE SourceTable(EmpId INT, BatchId INT,
Country NVARCHAR(100) NOT NULL, Pass NVARCHAR(5) NOT NULL);
INSERT INTO SourceTable(EmpId, BatchId, Country, Pass)
VALUES
(100, 1, 'UK', 'M'), (200, 2, 'USA', 'U'),
(100, 2, 'Romania', 'M'), (100, 3, 'India', 'MA'),
(100, 4, 'Hongkong', 'MA'), (300, 1, 'Belgium', 'U'),
(300, 2, 'Poland', 'U'), (200, 1, 'Australia', 'M');
/* Get Number of Columns Groups Country1..Country<MaxCount> */
DECLARE #max_count INT
,#sql NVARCHAR(MAX) = ''
,#columns NVARCHAR(MAX) = ''
,#i INT = 0
,#i_s NVARCHAR(10);
WITH cte AS
(
SELECT EmpId
,[cnt] = COUNT(*)
FROM SourceTable
GROUP BY EmpId
)
SELECT #max_count = MAX(cnt)
FROM cte;
WHILE #i < #max_count
BEGIN
SET #i += 1;
SET #i_s = CAST(#i AS NVARCHAR(10));
SET #columns += N',MAX(CASE WHEN [row_no] = ' + #i_s + ' THEN Country END) AS Country' + #i_s +
',MAX(CASE WHEN [row_no] = ' + #i_s + ' THEN Pass END) AS Pass' + #i_s;
END
SELECT #sql =
N';WITH cte AS (
SELECT EmpId, Country, Pass, [row_no] = ROW_NUMBER() OVER (PARTITION BY EmpId ORDER BY BatchId)
FROM SourceTable)
SELECT EmpId ' + #columns + N'
FROM cte
GROUP BY EmpId';
/* Debug */
/* SELECT #sql */
EXEC(#sql);
Or:
SQLFiddleDemo2
DECLARE #cols NVARCHAR(MAX),
#sql NVARCHAR(MAX) = '';
;WITH cte(col_name, rn) AS(
SELECT DISTINCT col_name = col_name + CAST(BatchId AS VARCHAR(10)),
rn = ROW_NUMBER() OVER(PARTITION BY EmpId ORDER BY BatchId)
FROM SourceTable
CROSS APPLY (VALUES ('Country', Country), ('Pass', Pass)) AS c(col_name, val)
)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(col_name)
FROM cte
ORDER BY rn /* If column order is important for you */
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SET #sql =
N';WITH cte AS
(
SELECT EmpId, col_name = col_name + CAST(BatchId AS VARCHAR(10)), val
FROM SourceTable
CROSS APPLY (VALUES (''Country'', Country), (''Pass'', Pass)) AS c(col_name, val)
)
SELECT *
FROM cte
PIVOT
(
MAX(val)
FOR col_name IN (' + #cols + ')
) piv';
EXEC(#sql);
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.)
I'm trying to anonymize all the data in my database, so I'm renaming all the people in it. I asked a similar question earlier, and was told to use NewID to force the creation of a new value per updated row, but in this situation it doesn't seem to be working.
What am I doing wrong?
-- Create Table Customer
CREATE TABLE #FirstName
(
ID int,
FirstName nvarchar(255) NULL,
Gender nvarchar(255) NULL
)
CREATE TABLE #LastName (
ID int,
LastName nvarchar(255)
)
-- BULK INSERT to import data from Text or CSV File
BULK INSERT #FirstName
FROM 'C:\Users\jhollon\Desktop\tmp\names\firstnames.lined.txt'
WITH
(
FIRSTROW = 1,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
BULK INSERT #LastName
FROM 'C:\Users\jhollon\Desktop\tmp\names\lastnames.lined.txt'
WITH
(
FIRSTROW = 1,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
/*SELECT FirstName FROM #FirstName WHERE ID = (
SELECT RandomNumber FROM (
SELECT ABS(CHECKSUM(NewID())) % 1500 AS RandomNumber FROM tblTenant WHERE Sex = '1'
) AS A
);*/
UPDATE tblTenant SET TenantName = (
SELECT LastName + ', ' + FirstName FROM
(SELECT UPPER(FirstName) as FirstName FROM #FirstName WHERE ID = (SELECT ABS(CHECKSUM(NewID())) % 500 + 1501)) AS A,
(SELECT LastName FROM #LastName WHERE ID = (SELECT ABS(CHECKSUM(NewID())) % 200 + 1)) as B
) WHERE Sex = '2';
UPDATE tblTenant SET TenantName = (
SELECT LastName + ', ' + FirstName FROM
(SELECT UPPER(FirstName) as FirstName FROM #FirstName WHERE ID = (SELECT ABS(CHECKSUM(NewID())) % 500 + 1)) AS A,
(SELECT LastName FROM #LastName WHERE ID = (SELECT ABS(CHECKSUM(NewID())) % 200 + 1)) as B
) WHERE Sex = '1';
DROP TABLE #FirstName;
DROP TABLE #LastName;
Correct. The subquery is evaluated once which is as advertised ("cachable scalar subquery")
Try this which uses NEWID as a derived table
UPDATE T
SET
TenantName = L.LastName + ', ' + F.FirstName
FROM
tblTenant T
CROSS APPLY
(SELECT TOP 1 UPPER(FirstName) as FirstName FROM #FirstName
WHERE CHECKSUM(NEWID()) <> T.ID
ORDER BY NEWID()) F
CROSS APPLY
(SELECT TOP 1 LastName FROM #LastName
WHERE CHECKSUM(NEWID()) <> T.ID
ORDER BY NEWID()) L
I'm not sure I understand your question, but if you want the ID to be unique values, you can make it an identity column.
Ex:
[ID] [int] IDENTITY(1,1) NOT NULL
The code below demonstrates that without an inner to outer correlation, that the old name is not guaranteed to differ from the new name when using the CROSS APPLY answer above.
WHERE F.Id <> T.Id ORDER BY NEWID() would be better within the FirstName CROSS APPLY
USE tempdb
GO
IF OBJECT_ID('tblTenant') IS NOT NULL
DROP TABLE tblTenant
GO
CREATE TABLE tblTenant
(
Id int,
FirstName nvarchar(20),
LastName nvarchar(20),
Gender bit
)
INSERT INTO tblTenant
VALUES (1, 'Bob' , 'Marley', 1),
(2, 'Boz' , 'Skaggs', 1)
SELECT DISTINCT FirstName
INTO #FirstNames
FROM tblTenant
SELECT DISTINCT LastName
INTO #LastNames
FROM tblTenant
-- There is a probability > 0 that a tenant's new name = tenants old name
SELECT
OldFirst = T.FirstName,
OldLast = T.LastName,
NewFirst = F.FirstName,
NewLast = L.LastName
FROM
tblTenant T
CROSS APPLY
(
SELECT TOP 1 UPPER(FirstName) AS FirstName
FROM #FirstNames
WHERE CHECKSUM(NEWID()) <> T.ID
ORDER BY NEWID()
) F
CROSS APPLY
(
SELECT TOP 1 LastName
FROM #LastNames
WHERE CHECKSUM(NEWID()) <> T.ID
ORDER BY NEWID()
) L
My function
ALTER FUNCTION GetProductCount
(#CatID int)
RETURNS int
AS
BEGIN
DECLARE #return_value int
EXEC #return_value = [dbo].[USP_Products_GetList]
#ProductName = NULL,
#ProductID = NULL,
#Description = NULL,
#CatID = #CatID,
#CatName = NULL,
#Price1 = NULL,
#Price2 = NULL,
#SizeID = NULL,
#IsNew = NULL,
#InActive = NULL,
#SortBy = NULL,
#SortType = NULL
return #return_value
end
Function Execution
GetProductCount 1
Msg 557, Level 16, State 2, Procedure
GetProductCount, Line 9 Only functions
and some extended stored procedures
can be executed from within a
function.
Question
I want to find total no. of rows
result by that stored procedure and return by this function.
What should i do now?
Solution please.........
you can't do it from a UDF unless you use a loopback linked server query hack, which is not recommended
My Stored Procedure which return rows according to category id = 1
USE [StoreDB]
GO
/****** Object: StoredProcedure [dbo].[USP_Products_GetList] Script Date: 08/21/2010 03:01:32 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[USP_Products_GetList]
#ProductName varchar(50),
#ProductID varchar(50),
#Description varchar(50),
#CatID varchar(50),
#CatName varchar(50),
#Price1 int,
#Price2 int,
#SizeID int,
#IsNew bit,
#InActive bit,
#SortBy varchar(50),
#SortType varchar(50)
AS
SELECT ProductID, ProductName, Price Price, PriceID, [Description], Size, SizeID, IsNew, InActive, ISNULL(ImageName,'Nophoto.png') AS ImageName, ImageTitle
FROM (
SELECT DISTINCT Products.ProductID, ProductName, MAX(Price) Price, PriceID, [Description], Size, Sizes.SizeID, IsNew, InActive, ImageName, ImageTitle FROM (SELECT * FROM Products WHERE (#InActive is null or #InActive = InActive ) AND ( #IsNew is null or #IsNew = IsNew )) Products
INNER JOIN ProductCategory
on Products.ProductID = ProductCategory.ProductID
LEFT OUTER JOIN (SELECT * FROM ProductImages
WHERE ( #ProductID is null or ProductID like '%' + #ProductID + '%' ) AND Isthumb = 'true'
) ProductImages
ON Products.ProductID = ProductImages.ProductID
INNER JOIN (
SELECT CatID FROM Categories
WHERE
( (#CatID is null or #CatID = 0) or #CatID = CatID ) and
( #CatName is null or CatName like '%' + #CatName + '%' )
) Categories
on ProductCategory.CatID = Categories.CatID
INNER JOIN (
SELECT Prices.ProductID, Prices.Price, Prices.PriceID, Prices.SizeID FROM Prices
INNER JOIN (
SELECT ProductID, MAX(Price) Price from Prices WHERE PriceID IN
( SELECT MAX(PriceID) FROM Prices
GROUP BY ProductID , SizeID)
GROUP BY ProductID ) Prices_
ON Prices.ProductID = Prices_.ProductID AND Prices.Price = Prices_.Price
) as Prices
on Prices.ProductID = Products.ProductID
inner join Sizes
on Sizes.SizeID = Prices.SizeID
GROUP BY ProductName, Products.ProductID, Price, PriceID, [Description] ,Size, Sizes.SizeID, IsNew, InActive, ImageName, ImageTitle
) AS OrderProduct WHERE
( #ProductName is null or ProductName like '%' + #ProductName + '%' ) and
( #ProductID is null or ProductID like '%' + #ProductID + '%' ) and
( #Description is null or [Description] like '%' + #Description + '%' ) and
( (#SizeID is null or #SizeID = 0)or SizeID = #SizeID ) and
( #Price1 is null or Price between #Price1 AND #Price2)
ORDER BY
CASE #SortType
WHEN 'desc' THEN
CASE #SortBy
WHEN 'ProductName' THEN ProductName
END
END
DESC,
CASE #SortType
WHEN 'desc' THEN
CASE #SortBy
WHEN 'ProductID' THEN ProductID
WHEN 'Price' THEN Price
END
END
DESC,
CASE #SortType
WHEN 'asc' THEN
CASE #SortBy
WHEN 'ProductName' THEN ProductName
END
END
ASC,
CASE #SortType
WHEN 'asc' THEN
CASE #SortBy
WHEN 'ProductID' THEN ProductID
WHEN 'Price' THEN Price
END
END
ASC