Query taking too long to execute with scalar function in where clause - sql-server

Below is my scalar function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [CheckClients]
(
#UserId Varchar(3),
#DbrNo varchar(10),
#V_DBR_CLIENT varchar(6)
)
RETURNS int
AS
BEGIN
Declare #Flag int
set #Flag=1
if(#V_DBR_CLIENT='XXXXXX')
BEGIN
if((select COUNT(USR_CLI)
from USRAGYCLI
inner join DBR on DBR_CLIENT = USR_CLI
where USR_CODE = #UserId and DBR_SERIES like #DbrNo +'T') <>
(select COUNT(DBR_CLIENT)
from DBR
where DBR_SERIES like #DbrNo + 'T') OR
(select COUNT(DBR_CLIENT)
from DBR
where DBR_SERIES like #DbrNo +'T') <= 0)
BEGIN
set #Flag=0
END
END
RETURN #Flag
END
This is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [SEL_CLI]
#V_USER_ID VARCHAR(3),
#V_NUMBER_OF_ROWS INT,
#V_STARTS_WITH INT
AS
BEGIN
CREATE TABLE #tmpDbrNo
(
Code VARCHAR(10),
Name VARCHAR(100),
NumberOfDebtors int,
rownum int
)
;WITH Temp AS
(
SELECT
CLT_NO AS Code,
CLT_NAME AS Name,
COUNT(DBR_NO) AS NumberOfDebtors
FROM
DBR
JOIN
USRAGYCLI ON DBR_CLIENT = USR_AGY_CLI
JOIN
CLT ON DBR_CLIENT = CLT_NO
WHERE
AND USR_CODE = #V_USER_ID
AND 1 = CheckClients(#V_USER_ID, DBR_NO, DBR_CLIENT)
GROUP BY
CLT_NO, CLT_NAME
)
INSERT INTO #tmpDbrNo
SELECT
Code, Name, NumberOfDebtors,
ROW_NUMBER() OVER (ORDER by Code) rownum
FROM
Temp
SELECT
Code, Name, NumberOfDebtors
FROM
#tmpDbrNo
WHERE
rownum BETWEEN #V_STARTS_WITH AND #V_STARTS_WITH + #V_NUMBER_OF_ROWS
END
Above query takes about 25 sec to execute which is too long to wait. And if I comment out the line where I have called the scalar function in the where clause, it takes 0 secs to execute the query.
Can anybody suggest better way which may take minimum secs to execute the query? I have tried to put call to function in case like as below, but no success.
AND 1 = CASE WHEN DBR_CLIENT='XXXXXX' THEN CheckClients(#V_USER_ID,DBR_NO,DBR_CLIENT) ELSE 1 END

This is just a shot in the dark because we were not provided with any ddl or much to work with. I think I interpreted the existing logic in your scalar function correctly. As a general rule you should probably avoid using flags. This is a very old school mindset and is not suited to relational data very well at all. I suspect this could be greatly improved with an understanding of the actual requirements but this is the best I could do with the limited details.
CREATE FUNCTION [CheckClients]
(
#UserId Varchar(3),
#DbrNo varchar(10),
#V_DBR_CLIENT varchar(6)
)
RETURNS table as return
with RowCounts as
(
select
(
select COUNT(DBR_CLIENT)
from DBR
where DBR_SERIES like #DbrNo + 'T'
) as ClientCount
,
(
select COUNT(USR_CLI)
from USRAGYCLI u
inner join DBR d on d.DBR_CLIENT = u.USR_CLI
where u.USR_CODE = #UserId
and d.DBR_SERIES like #DbrNo +'T'
) as UserCount
)
select case
when #V_DBR_CLIENT = 'XXXXXX' then
Case when rc.UserCount <> rc.ClientCount then 0
when rc.ClientCount < 0 then 0
else 1
end
else 1
end as Flag
from RowCounts rc

You can optimize your scalar function query to reduce doing multiple read. Like:
ALTER FUNCTION [CheckClients] (
#UserId VARCHAR(3),
#DbrNo VARCHAR(10),
#V_DBR_CLIENT VARCHAR(6)
)
RETURNS INT
AS
BEGIN
DECLARE #Flag INT
SET #Flag = 1
IF (#V_DBR_CLIENT = 'XXXXXX')
BEGIN
DECLARE #Count INT = ISNULL((
SELECT COUNT(DBR_CLIENT)
FROM DBR
WHERE DBR_SERIES LIKE #DbrNo + 'T'
), 0);
IF (
(ISNULL((
SELECT COUNT(USR_CLI)
FROM USRAGYCLI
INNER JOIN DBR ON DBR_CLIENT = USR_CLI
WHERE USR_CODE = #UserId
AND DBR_SERIES LIKE #DbrNo + 'T'
), 0) <> #Count)
OR (#Count <= 0)
)
BEGIN
SET #Flag = 0
END
END
RETURN #Flag
END
Also, you need to study your execution plan of the query to find out where the query is having high cost of execution time. And create non-clustered index if necessary.
-- EDITED LATER --
The non-Sargable Problem (Calling Scalar Function):
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [SEL_CLI]
#V_USER_ID VARCHAR(3),
#V_NUMBER_OF_ROWS INT,
#V_STARTS_WITH INT
AS
BEGIN
CREATE TABLE #tmpDbrNo
(
Code VARCHAR(10),
Name VARCHAR(100),
NumberOfDebtors int,
rownum int
)
;WITH Temp AS
(
SELECT
CLT_NO AS Code,
CLT_NAME AS Name,
COUNT(DBR_NO) AS NumberOfDebtors
FROM
DBR
JOIN
USRAGYCLI ON DBR_CLIENT = USR_AGY_CLI
JOIN
CLT ON DBR_CLIENT = CLT_NO
WHERE
USR_CODE = #V_USER_ID
AND 1 =
(CASE
WHEN (#V_DBR_CLIENT = 'XXXXXX') THEN
(CASE
WHEN (
ISNULL((
SELECT COUNT(USR_CLI)
FROM USRAGYCLI
INNER JOIN DBR ON DBR_CLIENT = USR_CLI
WHERE USR_CODE = #UserId
AND DBR_SERIES LIKE #DbrNo + 'T'
), 0) <> ISNULL((
SELECT COUNT(DBR_CLIENT)
FROM DBR
WHERE DBR_SERIES LIKE #DbrNo + 'T'
), 0)
)
OR (ISNULL((
SELECT COUNT(DBR_CLIENT)
FROM DBR
WHERE DBR_SERIES LIKE #DbrNo + 'T'
), 0) <= 0)
THEN 0
ELSE 1
END)
ELSE 1
END)--CheckClients(#V_USER_ID, DBR_NO, DBR_CLIENT)
GROUP BY
CLT_NO, CLT_NAME
)
INSERT INTO #tmpDbrNo
SELECT
Code, Name, NumberOfDebtors,
ROW_NUMBER() OVER (ORDER by Code) rownum
FROM
Temp
SELECT
Code, Name, NumberOfDebtors
FROM
#tmpDbrNo
WHERE
rownum BETWEEN #V_STARTS_WITH AND #V_STARTS_WITH + #V_NUMBER_OF_ROWS
END
As you can see, the scalar function can be included in the same query, but if you study the function nicely than it is clear that the query in scalar function is not fully dependent on the query in the store procedure. It is making count and will reread and manipulate the data from the table every time.
So, with this type of query making non-Sargable to Sargable will not improve the performance. The possible solution to the problem will be
To previously add the required data in the table and check from there.
To study your query plans(Design and Execution) and optimize it accordingly.

Related

How to return a table in SQL Server function

How would I return a table from a SQL Server function?
In Postgres, I would simply do something like the following:
CREATE FUNCTION table_get(_active_bool BOOLEAN)
RETURNS TABLE(column integer)
language plpgsql
as $$
BEGIN
RETURN QUERY
SELECT column
FROM table
WHERE active = _active_bool
END;
$$;
And it will just work.
For what ever reason I can't get this one to work in SQL Server.
CREATE FUNCTION hr.naughty_emp_id_get
(#pquarter NVARCHAR(1),
#pyear NVARCHAR(4))
RETURNS TABLE (employeeid INT)
AS
BEGIN
WITH vars AS
(
SELECT #pquarter AS pquarter, #pyear AS pyear
)
SELECT tblhr_employees.employeeid
FROM hr.tblhr_employees
INNER JOIN hr.tblHR_AttendancePunchTime ON tblhr_employees.employeeid = tblHR_AttendancePunchTime.EmployeeID
INNER JOIN hr.tblHR_AttendanceTimeCode ON tblHR_AttendancePunchTime.CodeID = tblHR_AttendanceTimeCode.CodeID
WHERE 1 = 1
AND (tblHR_AttendanceTimeCode.CategoryID = 3
OR tblHR_AttendanceTimeCode.CategoryID = 11)
AND dbo.to_year_quarter(tblHR_AttendancePunchTime.AdjTimeIn) = (SELECT vars.pyear FROM vars) + '-' + (SELECT vars.pquarter FROM vars)
AND tblhr_employees.separationdate IS NULL
GROUP BY
tblhr_employees.employeeid;
RETURN
END
GO
It is throwing this error:
Msg 156, Level 15, State 1, Procedure naughty_emp_id_get, Line 18 [Batch Start Line 6]
Incorrect syntax near the keyword 'BEGIN'
I tried adding ;s in various spots and it didn't seem to work
You are missing the table name for the table to be returned. This should work
CREATE FUNCTION hr.naughty_emp_id_get
(
-- Add the parameters for the function here
#pquarter NVARCHAR(1)
, #pyear NVARCHAR(4)
)
RETURNS #employees TABLE (employeeid INT)
AS
BEGIN
WITH vars AS (SELECT #pquarter AS pquarter, #pyear AS pyear)
INSERT #employees
SELECT tblhr_employees.employeeid
FROM hr.tblhr_employees
INNER JOIN hr.tblHR_AttendancePunchTime ON tblhr_employees.employeeid = tblHR_AttendancePunchTime.EmployeeID
INNER JOIN hr.tblHR_AttendanceTimeCode ON tblHR_AttendancePunchTime.CodeID = tblHR_AttendanceTimeCode.CodeID
WHERE 1=1
AND (tblHR_AttendanceTimeCode.CategoryID = 3
OR tblHR_AttendanceTimeCode.CategoryID = 11)
AND dbo.to_year_quarter(tblHR_AttendancePunchTime.AdjTimeIn) = (SELECT vars.pyear FROM vars) + '-' + (SELECT vars.pquarter FROM vars)
AND tblhr_employees.separationdate IS NULL
GROUP BY tblhr_employees.employeeid;
RETURN
END
You have mixed 2 ways of declaring the resulting temporal table.
Either declare as table variable and explicitly insert into it:
CREATE FUNCTION hr.naughty_emp_id_get
(
#pquarter NVARCHAR(1)
, #pyear NVARCHAR(4)
)
RETURNS #result TABLE (employeeid INT) -- Here
AS
BEGIN
;WITH vars AS (SELECT #pquarter AS pquarter, #pyear AS pyear)
INSERT INTO #result (employeeid) -- And here
SELECT tblhr_employees.employeeid
FROM --...
END
Or avoid it's declaration altogether:
CREATE FUNCTION hr.naughty_emp_id_get
(
-- Add the parameters for the function here
#pquarter NVARCHAR(1)
, #pyear NVARCHAR(4)
)
RETURNS TABLE AS RETURN
WITH vars AS (SELECT #pquarter AS pquarter, #pyear AS pyear)
SELECT tblhr_employees.employeeid
FROM --...
You have to insert into the resulting table variable.
RETURNS #MyTable TABLE (MyID INT)
AS BEGIN
INSERT INTO #MyTable SELECT 1
RETURN
END

Best way to deal with erroneous message "There is already an object named '#Tablename' in the database."

I have a recursive stored procedure running on SQL server 2005. I tested it and it works well. But when I tried to add another capability to it I get the message:
There is already an object named '#BOM' in the database.
The problem is that I need to create the initial temp table 2 different ways depending on parameters. The temp table is used for a set of reports the expand a BOM (Bill Of Materials). The BOM can consist of parts that are sub-assemblies that have thier own BOMs. In the simplest form I need this to work:
create PROCEDURE [dbo].[ExpandBOMTestError2]
(
#Similiar bit = 0
)AS
BEGIN
IF #Similiar = 0
SELECT '1' As Col INTO #BOM
ELSE
SELECT '2' As Col INTO #BOM
SELECT * FROM #BOM
END
I even tried this, although I would prefer to avoid something this ugly and cluttering I would accept it if it would work:
create PROCEDURE [dbo].[ExpandBOMTestError]
(
#Similiar bit = 0
)AS
BEGIN
IF #Similiar = 0
BEGIN
IF (SELECT object_id('TempDB..#BOM')) IS NOT NULL
DROP TABLE #BOM
SELECT '1' As Col INTO #BOM
END
ELSE
BEGIN
IF (SELECT object_id('TempDB..#BOM')) IS NOT NULL
DROP TABLE #BOM
SELECT '2' As Col INTO #BOM
END
SELECT * FROM #BOM
END
I am also enclosing the original procedure incase anyone wants to provide alternate solutions that may work in my stripped down example but not in real production code.
create PROCEDURE [dbo].[ExpandBOMList]
(
#ItemID varchar(100),
#Level int,
#EffectiveDate datetime = null,
#ExcludeIgnoreCost bit = 0,
#MaxBOMLevel int = 99,
#Similiar bit = 0
)AS
BEGIN
DECLARE #NewLevel int
IF #Level = 0
BEGIN
IF #Similiar = 0
SELECT #ItemID AS SubAssembly, #ItemID AS Component, Null AS EffectiveDate, 1 AS QPA, 0 AS BOMLevel INTO #BOM
ELSE
SELECT IMA_ItemID AS SubAssembly, IMA_ItemID AS Component, Null AS EffectiveDate, 1 AS QPA, 0 AS BOMLevel INTO #BOM FROM Item WHERE IMA_ItemID LIKE #ItemID + '%'
SET #NewLevel = #Level + 1
EXEC ExpandBOMList #ItemID, #NewLevel, #ExcludeIgnoreCost, #MaxBOMLevel
END
ELSE
BEGIN
INSERT #BOM SELECT ItemParent.IMA_ItemID, ItemChild.IMA_ItemID, Null, PST_QtyPerAssy, #Level
FROM ProductStructureHeader
JOIN ProductStructure ON PST_PSH_RecordID = PSH_RecordID
LEFT OUTER JOIN Item AS ItemParent ON PSH_IMA_RecordID = ItemParent.IMA_RecordID
LEFT OUTER JOIN Item AS ItemChild ON PST_IMA_RecordID = ItemChild.IMA_RecordID
JOIN #BOM ON ItemParent.IMA_ItemID = Component AND BOMLevel = #Level - 1
WHERE PST_QtyPerAssy <> 0 AND PST_EffStopDate IS NULL AND BOMLevel <= #MaxBOMLevel
IF ##rowcount > 0
BEGIN
SET #Level = #Level + 1
EXEC ExpandBOMList #ItemID, #Level, #ExcludeIgnoreCost, #MaxBOMLevel
END
END
IF #Level = 0
SELECT Component AS ItemID, IMA_ItemName AS ItemName, BOMLevel
FROM #BOM
JOIN Item on IMA_ItemID = Component
END
I hope someone has a good idea before I have to make this real ugly.
For the simple example I would do the following. I will look at the original procedure you posted and update my answer if I can offer any advice on that. It looks like some pretty complicated stuff you are doing. I would need time and data to try to figure something out other than what you are doing. Gut feeling is that using hierarchy might be appropriate.
Editing my original answer to account for recursive nature.
create PROCEDURE [dbo].[ExpandBOMTestError2]
(
#Similiar bit = 0
)AS
BEGIN
IF (SELECT object_id('TempDB..#BOM')) IS NULL
Create Table #BOM (Col Int)
IF #Similiar = 0
Insert #BOM SELECT '1'
ELSE
Insert #BOM SELECT '2'
SELECT * FROM #BOM
END

Using row count from a temporary table in a while loop SQL Server 2008

I'm trying to create a procedure in SQL Server 2008 that inserts data from a temp table into an already existing table. I think I've pretty much figured it out, I'm just having an issue with a loop. I need the row count from the temp table to determine when the loop should finish.
I've tried using ##ROWCOUNT in two different ways; using it by itself in the WHILE statement, and creating a variable to try and hold the value when the first loop has finished (see code below).
Neither of these methods have worked, and I'm now at a loss as to what to do. Is it possible to use ##ROWCOUNT in this situation, or is there another method that would work better?
CREATE PROCEDURE InsertData(#KeywordList varchar(max))
AS
BEGIN
--create temp table to hold words and weights
CREATE TABLE #tempKeywords(ID int NOT NULL, keyword varchar(10) NOT NULL);
DECLARE #K varchar(10), #Num int, #ID int
SET #KeywordList= LTRIM(RTRIM(#KeywordList))+ ','
SET #Num = CHARINDEX(',', #KeywordList, 1)
SET #ID = 0
--Parse varchar and split IDs by comma into temp table
IF REPLACE(#KeywordList, ',', '') <> ''
BEGIN
WHILE #Num > 0
BEGIN
SET #K= LTRIM(RTRIM(LEFT(#KeywordList, #Num - 1)))
SET #ID = #ID + 1
IF #K <> ''
BEGIN
INSERT INTO #tempKeywords VALUES (#ID, #K)
END
SET #KeywordList = RIGHT(#KeywordList, LEN(#KeywordList) - #Num)
SET #Num = CHARINDEX(',', #KeywordList, 1)
--rowcount of temp table
SET #rowcount = ##ROWCOUNT
END
END
--declaring variables for loop
DECLARE #count INT
DECLARE #t_name varchar(30)
DECLARE #key varchar(30)
DECLARE #key_weight DECIMAL(18,2)
--setting count to start from first keyword
SET #count = 2
--setting the topic name as the first row in temp table
SET #t_name = (Select keyword from #tempKeywords where ID = 1)
--loop to insert data from temp table into Keyword table
WHILE(#count < #rowcount)
BEGIN
SET #key = (SELECT keyword FROM #tempKeywords where ID = #count)
SET #key_weight = (SELECT keyword FROM #tempKeywords where ID = #count+2)
INSERT INTO Keyword(Topic_Name,Keyword,K_Weight)
VALUES(#t_name,#key,#key_weight)
SET #count= #count +2
END
--End stored procedure
END
To solve the second part of your problem:
INSERT INTO Keyword(Topic_Name,Keyword,K_Weight)
SELECT tk1.keyword, tk2.keyword, tk3.keyword
FROM
#tempKeywords tk1
cross join
#tempKeywords tk2
inner join
#tempKeywords tk3
on
tk2.ID = tk3.ID - 1
WHERE
tk1.ID = 1 AND
tk2.ID % 2 = 0
(This code should replace everything in your current script from the --declaring variables for loop comment onwards)
You could change:
WHILE(#count < #rowcount)
to
WHILE(#count < (select count(*) from #tempKeywords))
But like marc_s commented, you should be able to do this without a while loop.
I'd look at reworking your query to see if you can do this in a set based way rather than row by row.
I'm not sure I follow exactly what you are trying to achieve, but I'd be tempted to look at the ROW_NUMBER() function to set the ID of your temp table. Used with a recursive CTE such as shown in this answer you could get an id for each of your non empty trimmed words. An example is something like;
DECLARE #KeywordList varchar(max) = 'TEST,WORD, ,,,LIST, SOME , WITH, SPACES'
CREATE TABLE #tempKeywords(ID int NOT NULL, keyword varchar(10) NOT NULL)
;WITH kws (ord, DataItem, Data) AS(
SELECT CAST(1 AS INT), LEFT(#KeywordList, CHARINDEX(',',#KeywordList+',')-1) ,
STUFF(#KeywordList, 1, CHARINDEX(',',#KeywordList+','), '')
union all
select ord + 1, LEFT(Data, CHARINDEX(',',Data+',')-1),
STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from kws
where Data > ''
), trimKws(ord1, trimkw) AS (
SELECT ord, RTRIM(LTRIM(DataItem))
FROM kws
)
INSERT INTO #tempKeywords (ID, keyword)
SELECT ROW_NUMBER() OVER (ORDER BY ord1) as OrderedWithoutSpaces, trimkw
FROM trimKws WHERE trimkw <> ''
SELECT * FROM #tempKeywords
I don't fully understand what you are trying to acheive with the second part of your query , but but you could just build on this to get the remainder of it working. It certainly looks as though you could do what you are after without while statements at least.

Sql script syntax and grammar issues

Can someone help please I dont know what I am doing wrong:
IF EXISTS ( SELECT name
FROM sys.tables
WHERE name = N'MemberIdsToDelete' )
DROP TABLE [MemberIdsToDelete];
GO
SELECT mm.memberid ,
mm.aspnetuserid ,
mm.email ,
mm.RowNum AS RowNum
INTO #MemberIdsToDelete
FROM membership.members AS mm
LEFT JOIN aspnet_membership AS asp ON mm.aspnetuserid = asp.userid
LEFT JOIN trade.tradesmen AS tr ON tr.memberid = mm.memberid
WHERE asp.isapproved = 0
AND tr.ImportDPN IS NOT NULL
AND tr.importDPN <> ''
ORDER BY mm.memberid
DECLARE #MaxRownum INT
SET #MaxRownum = ( SELECT MAX(RowNum)
FROM #MemberIdsToDelete
)
DECLARE #Iter INT
SET #Iter = ( SELECT MIN(RowNum)
FROM #MemberIdsToDelete
)
DECLARE #MemberId INT
DECLARE #TrademId INT
DECLARE #UId UNIQUEIDENTIFIER
DECLARE #Successful INT
DECLARE #OutputMessage VARCHAR(200)
DECLARE #Email VARCHAR(100)
DECLARE #Username VARCHAR(100)
SELECT #MemberId = memberId ,
#UId = AspNetUserId
FROM MemberIdsToDelete
SELECT #TrademId = TradesManId
FROM trade.TradesMen
WHERE memberId = #MemberId;
WHILE #Iter <= #MaxRownum
BEGIN
SELECT *
FROM #MemberIdsToDelete
WHERE RowNum = #Iter
--more code here
SET #Iter = #Iter + 1
END
I just want to check if my table MemberIdsToDelete exists, if so drop it,
create MemberIdsToDelete with the results set from the select
loop through MemberIdsToDelete table and perform operations
I am getting error that RowNum does not exist
For a start, to check if a table exists and then drop accordingly, you need to use something like
IF EXISTS (SELECT name
FROM sys.tables
WHERE name = N'MemberIdsToDelete')
DROP TABLE [MemberIdsToDelete];
GO
as for the error, your RowNum column does not exist when you are attempting to reference it. Include it in the SELECT statement
select mm.memberid, mm.aspnetuserid, mm.email, mm.RowNum AS RowNum
into #MemberIdsToDelete
from membership.members as mm
left join aspnet_membership as asp
on mm.aspnetuserid=asp.userid
left join trade.tradesmen as tr
on tr.memberid=mm.memberid
where asp.isapproved = 0 and tr.ImportDPN IS NOT NULL
and tr.importDPN <> ''
order by mm.memberid;
GO
I hope this helps.
Edit. Based on you additional error from your comment. You are now attempting to access a temporary table that does not exist. You must first populate the temporary table #MemberIdsToDelete before attempting to read from it. The invalid column error is down to the same problem. You are attempting to read a column called RowNum from the temporary table which does not exist.
Edit2. Remove the '#' from the #MemberIdsToDelete. You are inserting into a table not a temporary table. Or, Add a # to the select into above (see the code above). This will make it a temporary table as required.
You don't have a RowNum column in that table.
Try:
select mm.memberid, mm.aspnetuserid, mm.email, row_number() over (order by (select 1)) as RowNum
....
This should solve your problem, but I wouldnt actually recommend this idea of looping through the ones to delete.

Why do my results not stay consistent?

I have the following stored procedure that I working on. I have noticed that every 5th or 6th time I refresh my results there are new values in there. Which considering that the data is in a static environment and no one is making any changes to the data at this time I really can't understand. Can someone please enlighten me as to why I would see different results even though I am running this procedure with the exact same parameters. I even tried it in query analyzer and still see the same strange results.
I am running in Sql 2008.
Here is the proc:
ALTER PROCEDURE [dbo].[SelectSearchBy_Category]
#userId INT,
#page INT,
#results INT,
#category NVARCHAR(50),
#searchTerm NVARCHAR(200) = NULL
AS
BEGIN
SET NOCOUNT ON
SET ROWCOUNT #results
DECLARE #categoryId INT
IF (#category IS NOT NULL) BEGIN
SET #categoryId = ( SELECT categoryId FROM Category WHERE categoryDescription = #category )
END
DECLARE #rowEnd INT
DECLARE #rowStart INT
SET #rowEnd = (#page * #results)
SET #rowStart = #rowEnd - #results
;WITH OrderedItems AS
(
SELECT
i.itemId,
title,
i.[description],
i.url,
i.categoryId,
i.ratingId,
i.requirements,
ISNULL(i.rating, 0) AS tating,
ISNULL(i.raters, 0) AS raters,
i.urlFriendlyPath,
ROW_NUMBER() OVER
(
ORDER BY i.dateAdded, (ISNULL(i.rating, 0) * ISNULL(i.raters, 0))
) AS RowNumber
FROM
[dbo].[Item] i
LEFT JOIN
UserItemIgnore uii ON uii.itemId = i.itemId AND uii.userId = #userId
INNER JOIN
ItemLanguage il ON il.itemId = i.itemId
WHERE
(#searchTerm IS NULL OR a.title LIKE '%' + #searchTerm + '%') AND
i.categoryId = #categoryId AND
il.languageId = 1 AND
uii.itemId IS NULL
)
SELECT *
FROM OrderedItems
WHERE RowNumber BETWEEN #rowStart AND #rowEnd
END
You will probably have consistent results if you put an order by clause in your OrderedItems temporary table definition.
Try using
ROW_NUMBER() OVER (ORDER BY i.dateAdded,
(ISNULL(i.rating, 0) * ISNULL(i.raters, 0)),
i.itemId)
i.itemId will act as a tie breaker to ensure that the results of ROW_NUMBER are deterministic in the event you have rows with equal ranks for i.dateAdded, (ISNULL(i.rating, 0) * ISNULL(i.raters, 0))

Resources