ambigious column name in sql server - sql

hello i'm having a ambiguous column name in m stored procedure for payment .bid-id can someone help to resolve this issue please?
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PaymentID] ASC
)AS RowNumber
,[PaymentID]
,[Name]
,[WinningPrice]
,[PaymentDate]
,[Payment.BidID]
INTO #Results
FROM Item INNER JOIN
Auction ON Item.ItemID = Auction.ItemID INNER JOIN
BID ON Auction.AuctionID = BID.AuctionID INNER JOIN
Payment ON BID.BidID = Payment.BidID
Where (BID.Status = 'Paid') AND (BID.BuyerID = #buyer)
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
End

There is a column name you use in the query that is available in multiple tables.
Without the table structure we can't be certain which one it is, but probably one with an alias in your query:
,[PaymentID]
,[Name]
,[WinningPrice]
,[PaymentDate]

Try this, Create a alias for ambiguous column name
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PaymentID] ASC
)AS RowNumber
,[PaymentID]
,[Name]
,[WinningPrice]
,[PaymentDate]
,[Payment.BidID] as PBidID
INTO #Results
FROM Item INNER JOIN
Auction ON Item.ItemID = Auction.ItemID INNER JOIN
BID ON Auction.AuctionID = BID.AuctionID INNER JOIN
Payment ON BID.BidID = Payment.BidID
Where (BID.Status = 'Paid') AND (BID.BuyerID = #buyer)
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
End

Good practice is using aliases like:
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY i.[PaymentID] ASC --which table it belongs? put correct alias
)AS RowNumber
,i.[PaymentID]
,i.[Name]
,i.[WinningPrice]
,i.[PaymentDate]
,p.[BidID]
INTO #Results
FROM Item i
INNER JOIN Auction a
ON i.ItemID = a.ItemID
INNER JOIN BID b
ON a.AuctionID = b.AuctionID
INNER JOIN Payment p
ON b.BidID = p.BidID
Where (b.Status = 'Paid')
AND (b.BuyerID = #buyer)
SELECT #RecordCount = COUNT(*)
FROM #Results

SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [PaymentID] ASC
)AS RowNumber
,[PaymentID]
,[Name]
,[WinningPrice]
,[PaymentDate]
,[Payment.BidID]
INTO #Results
FROM Item INNER JOIN
Auction ON Item.ItemID = Auction.ItemID INNER JOIN
BID ON Auction.AuctionID = BID.AuctionID INNER JOIN
**Payment P1 ON BID.BidID = P1.BidID**
Where (BID.Status = 'Paid') AND (BID.BuyerID = #buyer)
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
End
Hope this helps..
highlighted the line which i changed

Related

MS SQL SERVER PAGING

I did a query which is :
SELECT DISTINCT m.logID
FROM Monitor_data m
inner join Monitor_object o on (o.objID = m.domainID)
inner join Monitor_event e on (e.mainID = m.logID)
WHERE (o.name = #objName
and m.service = #service
and e.statement = #statement
and m.start >= #start
and m.end <= #end)
That allows me to get some id (VARCHAR(50)). But, now I want to make a pagination so I need to modify that query. Unfortunately, I cannot use LIMIT and OFFSET ... I may use ROW_NUMBER but I don't know how :/ It will be great to get a result corresponding to the rows at line n to m. Thus, I will be able to create a paging process easily.
Can someone help me ?
Thank you.
Try this query:
select logID from (
SELECT DISTINCT m.logID,
ROW_NUMBER() over (order by m.start) rn
FROM Monitor_data m
inner join Monitor_object o on (o.objID = m.domainID)
inner join Monitor_event e on (e.mainID = m.logID)
WHERE (o.name = #objName
and m.service = #service
and e.statement = #statement
and m.start >= #start
and m.end <= #end)
) a where rn between (m, n) --here you provide values for limits for rows to return
Above query is based on ROW_NUMBER function in SQL Server, which requires some ordering, so I assumed that m.start will provide an order (I think it start date or something :) ).
Use #PageIndex and PageSize for paging
declare #PageIndex int=1
declare #PageSize int=10
declare #RecordCount int
SET NOCOUNT ON;
SELECT
ROW_NUMBER() OVER (ORDER BY m.logID ) as RowNumber, DISTINCT m.logID
INTO #Results
FROM Monitor_data m
inner join Monitor_object o on (o.objID = m.domainID)
inner join Monitor_event e on (e.mainID = m.logID)
WHERE (o.name = #objName
and m.service = #service
and e.statement = #statement
and m.start >= #start
and m.end <= #end)
SELECT #RecordCount = COUNT(*) FROM #Results
SELECT
*, #RecordCount as RecordCount FROM #Results
WHERE
RowNumber BETWEEN (#PageIndex -1) * #PageSize + 1 AND (((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
I think this is what you want.
Select logId from
(SELECT DISTINCT m.logID, Row_number() over (order by (select null)) as ranking
FROM Monitor_data m
inner join Monitor_object o on (o.objID = m.domainID)
inner join Monitor_event e on (e.mainID = m.logID)
WHERE (o.name = #objName
and m.service = #service
and e.statement = #statement
and m.start >= #start
and m.end <= #end))
where ranking between n and m
ORDER BY ******
OFFSET #ItemsPerPage * (#CurrentPage - 1) ROWS
FETCH NEXT #ItemsPerPage ROWS ONLY
DECLARE #CurrentPage int = 1;
DECLARE #ItemsPerPage int = 10;
SELECT DISTINCT m.logID
FROM Monitor_data m
inner join Monitor_object o on (o.objID = m.domainID)
inner join Monitor_event e on (e.mainID = m.logID)
WHERE (o.name = #objName
and m.service = #service
and e.statement = #statement
and m.start >= #start
and m.end <= #end)
ORDER BY m.logID
OFFSET #ItemsPerPage * (#CurrentPage - 1) ROWS
FETCH NEXT #ItemsPerPage ROWS ONLY
paging Example
DECLARE #myTable TABLE(Id int, Name nvarchar(50),EventDate date);
INSERT INTO #myTable(Id, Name, EventDate)
VALUES (1, 'a', '2018-01-01'),
(2, 'b', '2018-01-02'),
(3, 'c', '2018-01-03'),
(4, 'd', '2018-01-04'),
(5, 'e', '2018-01-05'),
(6, 'f', '2018-01-06');
DECLARE #CurrentPage int = 1;
DECLARE #ItemsPerPage int = 4;
SELECT * FROM #myTable
ORDER BY EventDate DESC
OFFSET #ItemsPerPage * (#CurrentPage - 1) ROWS
FETCH NEXT #ItemsPerPage ROWS ONLY
Starting with 2012, you could use OFFSET and FETCH. Prior to that a solution is to use ROW_NUMBER. However, beware, ROW_NUMBER() approach is very slow. If you don't have a performance problem you can use it.
Whatever the version is, a fast paging is done using TOP N and ordering by your desired columns and also specifying minimum value. ie:
select TOP (#pageSize) * from myTable
where myKeyValue > #minValue
order by myKeyValue;

Select columns without group by in aggregate

I'm using SQL Server 2014. I have a structure like this:
Id BIGINT,
ItemName NVARCHAR(4000),
RecordDate DATETIME2,
Supplier NVARCHAR(450),
Quantity DECIMAL(18, 2),
ItemUnit NVARCHAR(2000),
EntityUnit NVARCHAR(2000),
ItemSize DECIMAL(18, 2),
PackageSize DECIMAL(18, 2),
FamilyCode NVARCHAR(20),
Family NVARCHAR(500),
CategoryCode NVARCHAR(20),
Category NVARCHAR(500),
SubCategoryCode NVARCHAR(20),
SubCategory NVARCHAR(500),
ItemGroupCode NVARCHAR(20),
ItemGroup NVARCHAR(500),
PurchaseValue DECIMAL(18, 2),
UnitPurchaseValue DECIMAL(18, 2),
PackagePurchaseValue DECIMAL(18, 2),
FacilityCode NVARCHAR(450),
CurrencyCode NVARCHAR(5)
I'd like to select distinct ItemNames from BatchRecords table paired with the max Id among the items with the same ItemName as well as Supplier, Quantity and other values of the item with the max Id for each ItemName. So far, I came up with the following SP, definitely it doesn't work yet as GROUP BY throws an error.
I could probably use a subquery, but then how do I satisfy the condition with max Ids for each unique ItemName? Also, any input to the stored procedure quality/obvious bottleneck is highly appreciated as it has to be somewhat quick.
CREATE PROCEDURE dbo.GetRecordsPageFlat
(#BatchIds dbo.GenericIntArray READONLY,
#FileRequestId INT,
#PageSize INT,
#PageCount INT,
#LastId BIGINT,
#NameMaskValue NVARCHAR(128) = NULL,
#NameMaskType INT = NULL,
#FamilyCodeMaskValue NVARCHAR(128),
#CategoryCodeMaskValue NVARCHAR(128),
#SubCategoryCodeMaskValue NVARCHAR(128)
)
AS
SET NOCOUNT ON;
DECLARE #Temp dbo.RecordImportStructure
DECLARE #ErrorCode INT
DECLARE #Step NVARCHAR(200)
DECLARE #Rows INT
--OUTPUT ##ROWCOUNT
--OUTPUT INSERTED.Id
INSERT INTO #Temp (
Id,
ItemName,
Supplier,
Quantity,
ItemUnit,
EntityUnit,
ItemSize,
PackageSize,
PurchaseValue,
UnitPurchaseValue,
PackagePurchaseValue,
CurrencyCode
)
SELECT
BR.Id,
BR.ItemName,
BR.Supplier,
BR.Quantity,
BR.ItemUnit,
BR.EntityUnit,
BR.ItemSize,
BR.PackageSize,
BR.ItemGroup,
BR.UnitPurchaseValue,
BR.PackagePurchaseValue,
C.IsoCode
FROM
dbo.BatchRecords BR
LEFT OUTER JOIN
dbo.FacilityInstances F ON F.Id = BR.FacilityInstanceId
LEFT OUTER JOIN
dbo.Currencies C ON C.Id = BR.CurrencyId
--OPTION(RECOMPILE)
WHERE
BR.DataBatchId IN (SELECT * FROM #BatchIds)
AND BR.Id > #LastId
AND (#FamilyCodeMaskValue IS NULL OR BR.FamilyCode = #FamilyCodeMaskValue)
AND (#CategoryCodeMaskValue IS NULL OR BR.CategoryCode = #CategoryCodeMaskValue)
AND (#SubCategoryCodeMaskValue IS NULL OR BR.SubCategoryCode = #SubCategoryCodeMaskValue)
AND (#NameMaskType IS NULL AND #NameMaskValue IS NULL
OR ((#NameMaskType = 1 AND BR.ItemName LIKE #NameMaskValue + '%')
OR (#NameMaskType = 2 AND BR.ItemName LIKE '%' + #NameMaskValue)
OR (#NameMaskType = 3 AND BR.ItemName LIKE '%' + #NameMaskValue + '%')
))
GROUP BY
BR.ItemName
ORDER BY
BR.Id
OFFSET #PageCount * #PageSize ROWS
FETCH NEXT #PageSize ROWS ONLY;
UPDATE dbo.BatchActionRequests
SET PageNumber = #PageCount+1,
LatestItemId = (SELECT MAX(Id) FROM #Temp)
WHERE Id = #FileRequestId
It looks like a top-n-per-group problem.
There are two common approaches to it: using ROW_NUMBER and CROSS APPLY. Here is the ROW_NUMBER variant. See Get top 1 row of each group for details.
WITH
CTE
AS
(
SELECT
BR.Id,
BR.ItemName,
BR.Supplier,
BR.Quantity,
BR.ItemUnit,
BR.EntityUnit,
BR.ItemSize,
BR.PackageSize,
-- BR.ItemGroup,???
BR.UnitPurchaseValue,
BR.PackagePurchaseValue,
C.IsoCode AS CurrencyCode,
ROW_NUMBER() OVER (PARTITION BY BR.ItemName ORDER BY BR.Id DESC) AS rn
FROM
dbo.BatchRecords BR
LEFT OUTER JOIN dbo.FacilityInstances F ON F.Id = BR.FacilityInstanceId
LEFT OUTER JOIN dbo.Currencies C ON C.Id = BR.CurrencyId
WHERE
BR.DataBatchId IN (SELECT * FROM #BatchIds)
AND BR.Id > #LastId
AND (#FamilyCodeMaskValue IS NULL OR BR.FamilyCode = #FamilyCodeMaskValue)
AND (#CategoryCodeMaskValue IS NULL OR BR.CategoryCode = #CategoryCodeMaskValue)
AND (#SubCategoryCodeMaskValue IS NULL OR BR.SubCategoryCode = #SubCategoryCodeMaskValue)
AND (#NameMaskType IS NULL AND #NameMaskValue IS NULL
OR ((#NameMaskType = 1 AND BR.ItemName LIKE #NameMaskValue + '%')
OR (#NameMaskType = 2 AND BR.ItemName LIKE '%' + #NameMaskValue)
OR (#NameMaskType = 3 AND BR.ItemName LIKE '%' + #NameMaskValue + '%')
))
)
INSERT INTO #Temp (
Id,
ItemName,
Supplier,
Quantity,
ItemUnit,
EntityUnit,
ItemSize,
PackageSize,
-- PurchaseValue,???
UnitPurchaseValue,
PackagePurchaseValue,
CurrencyCode
)
SELECT
Id,
ItemName,
Supplier,
Quantity,
ItemUnit,
EntityUnit,
ItemSize,
PackageSize,
-- PurchaseValue,???
UnitPurchaseValue,
PackagePurchaseValue,
CurrencyCode
FROM CTE
WHERE rn = 1
ORDER BY
Id
OFFSET #PageCount * #PageSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(RECOMPILE);
For each ItemName the query will pick the row with the largest Id.
;WITH CTC
AS
(
SELECT MAX(BR.ID) AS Id, BR.ItemName
FROM dbo.BatchRecords BR
LEFT OUTER JOIN dbo.FacilityInstances F ON F.Id = BR.FacilityInstanceId
WHERE BR.DataBatchId IN (SELECT * FROM #BatchIds)
AND BR.Id > #LastId
AND (#FamilyCodeMaskValue IS NULL OR BR.FamilyCode = #FamilyCodeMaskValue)
AND (#CategoryCodeMaskValue IS NULL OR BR.CategoryCode = #CategoryCodeMaskValue)
AND (#SubCategoryCodeMaskValue IS NULL OR BR.SubCategoryCode = #SubCategoryCodeMaskValue)
AND (#NameMaskType IS NULL AND #NameMaskValue IS NULL
OR ((#NameMaskType = 1 AND BR.ItemName LIKE #NameMaskValue + '%')
OR (#NameMaskType = 2 AND BR.ItemName LIKE '%' + #NameMaskValue)
OR (#NameMaskType = 3 AND BR.ItemName LIKE '%' + #NameMaskValue + '%')
))
GROUP BY
BR.ItemName
)
INSERT INTO #Temp (
Id,
ItemName,
Supplier,
Quantity,
ItemUnit,
EntityUnit,
ItemSize,
PackageSize,
PurchaseValue,
UnitPurchaseValue,
PackagePurchaseValue,
CurrencyCode
)
SELECT BR.Id,
BR.ItemName,
BR.Supplier,
BR.Quantity,
BR.ItemUnit,
BR.EntityUnit,
BR.ItemSize,
BR.PackageSize,
BR.ItemGroup,
BR.UnitPurchaseValue,
BR.PackagePurchaseValue,
C.IsoCode
FROM CTC t
JOIN dbo.BatchRecords BR ON t.Id = BR.Id
LEFT OUTER JOIN dbo.Currencies C ON C.Id = BR.CurrencyId
ORDER BY BR.Id
OFFSET #PageCount * #PageSize ROWS
FETCH NEXT #PageSize ROWS ONLY;

SQL - More efficient way instead of using a cursor

-- Declare the table we are interested in reverting.
DECLARE #table_name VARCHAR(1000)
SET #table_name = 'tblCustomers' -- change this
-- Declare cursor and use the select statement (the one we want to loop through).
DECLARE customer_cursor CURSOR FOR
SELECT C.CustomerId
FROM tblCustomers C
WHERE ModifiedBy like '%crm%'
ORDER BY C.CustomerId DESC
-- Open the cursor and copy the columns into the original_consumer variable.
DECLARE #customer_id INT
OPEN customer_cursor
FETCH NEXT FROM customer_cursor
INTO #customer_id
-- Now loop through the old consumer id's and update their corresponding purchase and refunds records.
WHILE ##FETCH_STATUS = 0
BEGIN
IF EXISTS ( SELECT TOP 1 UserName
FROM tblAudit
WHERE TableName = #table_name
AND TableId IN (
SELECT CONVERT(VARCHAR, CustomerId)
FROM tblCustomers -- change this
WHERE CustomerId = #customer_id
)
AND UserName != 'crmuser'
ORDER BY TransactionDate DESC)
BEGIN
UPDATE tblCustomers
SET ModifiedBy = (SELECT TOP 1 UserName
FROM tblAudit
WHERE TableName = #table_name
AND TableId IN (
SELECT CONVERT(VARCHAR, CustomerId)
FROM tblCustomers -- change this
WHERE CustomerId = #customer_id
)
AND UserName != 'crmuser'
ORDER BY TransactionDate DESC),
ModifiedDate = (SELECT TOP 1 TransactionDate
FROM tblAudit
WHERE TableName = #table_name
AND TableId IN (
SELECT CONVERT(VARCHAR, CustomerId)
FROM tblCustomers -- change this
WHERE CustomerId = #customer_id
)
AND UserName != 'crmuser'
ORDER BY TransactionDate DESC)
WHERE CustomerId = #customer_id
END
FETCH NEXT FROM customer_cursor INTO #customer_id
END
-- Finally close and deallocate the cursor to stop memory leakage.
CLOSE customer_cursor
DEALLOCATE customer_cursor
This looks like it might work:
UPDATE tblCustomers
SET ModifiedBy = a.UserName,
ModofiedDate = amax.LatestChangeDate
from tblCustomers t
inner join -- get the latest transaction_date for each customer
(
select customerId, max(transaction_date) LatestChangeDate
from tblAudit
where TableName = #table_name
) amax on amax.customerId = t.customer_id
inner join -- get the details of changes for customer and latest date
(
select CustomerId, UserName, transaction_date
from tblAudit
where table_name = #table_name
) a on a.customerId = t.customerId and a.transaction_date = amax.LatestChangeDate
WHERE t.CustomerId = #customer_id
);
(I might have some of the column names wrong.)
BEGIN TRAN
SELECT COUNT(*)
FROM tblInvoices
WHERE ModifiedBy = 'DataImporterUser'
;WITH cte AS
(
SELECT TableId,
TransactionDate,
UserName,
TransactionDetail,
ROW_NUMBER() OVER (PARTITION BY TableId ORDER BY TransactionDate DESC) AS rn
FROM tblAudit
WHERE TableName = 'tblInvoices'
AND UserName <> 'DataImporterUser'
)
UPDATE C
SET C.ModifiedBy = cte.UserName,
C.ModifiedDate = cte.TransactionDate
FROM tblInvoices AS C
INNER JOIN cte
ON cte.TableId = C.InvoiceId
WHERE rn = 1
SELECT COUNT(*)
FROM tblEvents
WHERE ModifiedBy = 'DataImporterUser'
ROLLBACK

How to set the out parameter when using ROW_NUMBER() & COUNT(*)

How can I set the out #Total parameter of this tsql proc when using the ROW_NUMBER() OVER along with COUNT(*)?
ALTER proc [Generic].[proc_GetPartsForUser_BySupplier_ByCategory]
#UserID UNIQUEIDENTIFIER,
#SupplierID INT,
#CategoryID INT,
#StartIndex INT,
#PageSize INT,
#Total INT out
AS
SET NOCOUNT ON;
SET #StartIndex = #StartIndex + 1
BEGIN
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY ID ASC) AS RowNum, COUNT(*) OVER() AS Total
FROM (
SELECT p.*,
s.Name'SupplierName',s.Email'SupplierEmail',s.Phone'SupplierPhone'
FROM [Generic].[Part] p WITH(NOLOCK) JOIN
Generic.Supplier s WITH(NOLOCK) ON p.SupplierID = s.ID
WHERE p.ID IN(SELECT up.PartID FROM Generic.GenericCatalog gc with(nolock) JOIN
Generic.UserPart up WITH(NOLOCK) ON up.GenericCatID = gc.ID
WHERE gc.UserID = #UserID)
AND
CategoryID = #CategoryID
AND
s.ID = #SupplierID
) AS firstt
) AS final
WHERE RowNum BETWEEN #StartIndex AND (#StartIndex + #pageSize) - 1
ORDER BY final.[Name] ASC;
END;
SET NOCOUNT OFF;
The simple answer is you can't!
The OVER() clause creates a windowed function, meaning it will return the value for every row! The parameter can only store one value!
The question remains, why do you want to do this?
If the point of the entire query is to return the value of COUNT(*), then just use it without the OVER clause like this:
SELECT #Total = COUNT(*)
FROM (SELECT p.*,
s.NAME 'SupplierName',
s.EMAIL'SupplierEmail',
s.PHONE'SupplierPhone'
FROM [Generic].[PART] p WITH(NOLOCK)
JOIN GENERIC.SUPPLIER s WITH(NOLOCK)
ON p.SUPPLIERID = s.ID
WHERE p.ID IN(SELECT up.PARTID
FROM GENERIC.GENERICCATALOG gc WITH(NOLOCK)
JOIN GENERIC.USERPART up WITH(NOLOCK)
ON up.GENERICCATID = gc.ID
WHERE gc.USERID = #UserID)
AND CATEGORYID = #CategoryID
AND s.ID = #SupplierID) AS firstt
If what you need is more than this, edit your question and I'll try to find you a better answer.

Sql query - return 2 table

declare #PageIndex int
declare #PageSize int
declare #CategoryID int
declare #FromReleaseDate datetime
declare #TillRelaseDate datetime
set #CategoryID =6
set #FromReleaseDate = '1.01.2000'
set #TillRelaseDate = '1.01.2022'
set #PageIndex =1
set #PageSize=2
begin
with filtered as (
select ArticleList.ID as ID, ArticleList.CategoryID as CategoryID
from (
select a.*, c.ID as cID, c.ParentID as ParentID,
ROW_NUMBER() over(order by ReleaseOn desc) as RowNum
from Article as a
inner join Category as c
on a.CategoryID=c.ID and (#CategoryID is null or a.CategoryID = #CategoryID )
where (a.ReleaseOn>=#FromReleaseDate)
and (a.ReleaseOn <=#TillRelaseDate )
)
as ArticleList
where ArticleList.RowNum between
(#PageIndex - 1) * #PageSize + 1 and #PageIndex*#PageSize
)
select c.* from Article as a
inner join Category as c on a.CategoryID=c.ID
where
c.id in (select CategoryID from filtered)
select a.*
from Article as a
inner join Category as c on a.CategoryID=c.ID
where a.id in (select id from filtered)
end
I have to return 2 tables. But I can't do it, because filtered in the second query is not accessible. Is there any way to fix this error?
Using table variable...
declare #filtered as table (
ID int
, CategoryID int
)
insert into #filtered
select ArticleList.ID as ID, ArticleList.CategoryID as CategoryID
from (
select a.*, c.ID as cID, c.ParentID as ParentID,
ROW_NUMBER() over(order by ReleaseOn desc) as RowNum
from Article as a
inner join Category as c
on a.CategoryID=c.ID and (#CategoryID is null or a.CategoryID = #CategoryID )
where (a.ReleaseOn>=#FromReleaseDate)
and (a.ReleaseOn <=#TillRelaseDate )
)
as ArticleList
where ArticleList.RowNum between
(#PageIndex - 1) * #PageSize + 1 and #PageIndex*#PageSize
with filtered as (
select * from #filtered
)
... Rest of the query
select * from #filtered
Use table variables or create a view (if you have permissions) that represents the query you have in your CTE currently.