TSQL - Optimizing Full Text Search query with temp table - sql-server

To make it short I have a full text search query that does a company search on a single table. Once the search is complete I pull extra stats from the result such as Top 5 titles, top 5 locations etc...
How can this query be optimized it currently takes about 5 seconds to execute on < 25,000 rows and based on the execution plan its mostly on the last 3 select statements.
SQL SERVER: 2005. I can upgrade to 2008 but I've heard there are more performance issues with SQL 2008.
Help is greatly appreciated.
CREATE PROCEDURE [usp_Company_Search]
#KeywordNear as varchar(250),
#LocationNear as varchar(250) = null,
#PageIndex as int,
#Pagesize as int
AS
BEGIN
DECLARE #tbl TABLE
(
row int,
[Rank] int,
CompanyID int,
CompanyDesc text,
Title nvarchar(150),
Company nvarchar(150),
Category nvarchar(50),
Source nvarchar(50),
URI nvarchar(250),
Location varchar(60),
DateCreated nvarchar(50)
)
IF (#LocationNear is not null) BEGIN
WITH CompanySearch as
(
SELECT ROW_NUMBER() OVER (ORDER BY rs.rank desc) as row,
rs.Rank as [Rank],
J.CompanyID,
J.CompanyDesc,
J.Title,
J.Company,
J.Category,
J.Source,
J.URI,
J.Location,
J.DateCreated
FROM Company J
INNER JOIN
CONTAINSTABLE (Company,RawStripped, #KeywordNear) rs
ON J.Companyid = rs.[KEY] AND
CONTAINS (Location, #LocationNear)
)
insert into #tbl select * from CompanySearch
SELECT
CompanySearch.[Rank],
CompanySearch.CompanyID,
CompanySearch.CompanyDesc,
CompanySearch.Title,
CompanySearch.Company,
CompanySearch.Category,
CompanySearch.Source,
CompanySearch.URI,
CompanySearch.Location,
CompanySearch.DateCreated
FROM #tbl as CompanySearch
WHERE CompanySearch.row between (#PageIndex - 1) * #PageSize + 1 and #PageIndex*#PageSize
END
ELSE
BEGIN
WITH CompanySearch as
(
SELECT ROW_NUMBER() OVER (ORDER BY rs.rank desc) as row,
rs.Rank,
J.CompanyID,
J.CompanyDesc,
J.Title,
J.Company,
J.Category,
J.Source,
J.URI,
J.Location,
J.DateCreated
FROM Company J
INNER JOIN
CONTAINSTABLE (Company,RawStripped, #KeywordNear) rs
ON J.Companyid = rs.[KEY]
)
insert into #tbl select * from CompanySearch
SELECT
CompanySearch.Rank,
CompanySearch.CompanyID,
CompanySearch.CompanyDesc,
CompanySearch.Title,
CompanySearch.Company,
CompanySearch.Category,
CompanySearch.Source,
CompanySearch.URI,
CompanySearch.Location,
CompanySearch.DateCreated
FROM #tbl as CompanySearch
WHERE CompanySearch.row between (#PageIndex - 1) * #PageSize + 1 and #PageIndex*#PageSize
END
SELECT Max(row) as RecordCount from #tbl
select top 5 title, count(title) as cnt from #tbl group by title order by cnt desc
SELECT top 5 Location, count(location) as cnt from #tbl group by location order by cnt desc
SELECT top 5 Company, count(company) as cnt from #tbl group by company order by cnt desc
END

Your execution plan results may be deceiving. In SQL 2005, the fulltext engine is an external service, so SQL cannot accurately report on what's happening in that piece of the puzzle.
I'm not sure what performance issues you've heard of in 2008, but in 2008 the fulltext engine becomes fully integrated with the database, making it much more efficient in a case like yours where you're joining a database table against a set of fulltext results. If upgrading is an option for you, I'd encourage you to pursue that option.
See: SQL Server 2008 Full-Text Search: Internals and Enhancements

Related

How do I loop through a table, search with that data, and then return search criteria and result to new table?

I have a set of records that need to be validated (searched) in a SQL table. I will call these ValData and SearchTable respectively. A colleague created a SQL query in which a record from the ValData can be copied and pasted in to a string variable, and then it is searched in the SearchTable. The best result from the SearchTable is returned. This works very well.
I want to automate this process. I loaded the ValData to SQL in a table like so:
RowID INT, FirstName, LastName, DOB, Date1, Date2, TextDescription.
I want to loop through this set of data, by RowID, and then create a result table that is the ValData joined with the best match from the SearchTable. Again, I already have a query that does that portion. I just need the loop portion, and my SQL skills are virtually non-existent.
Suedo code would be:
DECLARE #SearchID INT = 1
DECLARE #MaxSearchID INT = 15000
DECLARE #FName VARCHAR(50) = ''
DECLARE #FName VARCHAR(50) = ''
etc...
WHILE #SearchID <= #MaxSearchID
BEGIN
SET #FNAME = (SELECT [Fname] FROM ValData WHERE [RowID] = #SearchID)
SET #LNAME = (SELECT [Lname] FROM ValData WHERE [RowID] = #SearchID)
etc...
Do colleague's query, and then insert(?) search criteria joined with the result from the SearchTable in to a temporary result table.
END
SELECT * FROM FinalResultTable;
My biggest lack of knowledge comes in how do I create a temporary result table that is ValData's fields + SearchTable's fields, and during the loop iterations how do I add one row at a time to this temporary result table that includes the ValData joined with the result from the SearchTable?
If it helps, I'm using/wanting to join all fields from ValData and all fields from SearchTable.
Wouldn't this be far easier with a query like this..?
SELECT FNAME,
LNAME
FROM ValData
WHERE (FName = #Fname
OR LName = #Lname)
AND RowID <= #MaxSearchID
ORDER BY RowID ASC;
There is literally no reason to use a WHILE other than to destroy performance of the query.
With a bit more trial and error, I was able to answer what I was looking for (which, at its core, was creating a temp table and then inserting rows in to it).
CREATE TABLE #RESULTTABLE(
[feedname] VARCHAR(100),
...
[SCORE] INT,
[Max Score] INT,
[% Score] FLOAT(4),
[RowID] SMALLINT
)
SET #SearchID = 1
SET #MaxSearchID = (SELECT MAX([RowID]) FROM ValidationData
WHILE #SearchID <= #MaxSearchID
BEGIN
SET #FNAME = (SELECT [Fname] FROM ValidationData WHERE [RowID] = #SearchID)
...
--BEST MATCH QUERY HERE
--Select the "top" best match (order not guaranteed) in to the RESULTTABLE.
INSERT INTO #RESULTTABLE
SELECT TOP 1 *, #SearchID AS RowID
--INTO #RESULTTABLE
FROM #TABLE3
WHERE [% Score] IN (SELECT MAX([% Score]) FROM #TABLE3)
--Drop temp tables that were created/used during best match query.
DROP TABLE #TABLE1
DROP TABLE #TABLE2
DROP TABLE #TABLE3
SET #SearchID = #SearchID + 1
END;
--Join the data that was validated (searched) to the results that were found.
SELECT *
FROM ValidationData vd
LEFT JOIN #RESULTTABLE rt ON rt.[RowID] = vd.[RowID]
ORDER BY vd.[RowID]
DROP TABLE #RESULTTABLE
I know this could be approved by doing a join, probably with the "BEST MATCH QUERY" as an inner query. I am just not that skilled yet. This takes a manual process which took hours upon hours and shortens it to just an hour or so.

Paging in SQL Server

Hello guys help me with this problem.
I have table name comments in SQL.
I applied paging in SQL procedure.
step-1:Firstly i fetch page 1 with 5 records
step-2:Now Created new comment.
step-3:Fetch page 2 with 5 records.
step-4:Got 5 rows that is fine but i got one record again which was in page 1 also
This happens because every time i create new comment the last comments will be shifted by one and each time i am facing this kind problem.
Ex.
create proc getComments(#PageNumber tinyint,#PerPage INT,#TotalRecords INT OUTPUT)
AS
CREATE TABLE #TempTable
(RowNumber SMALLINT,Id int,CommentText nvarchar(max),CommentedBy nvarchar(256),CommentTime datetime
INSERT INTO #TempTable
(RowNumber,Id ,CommentText ,CommentedBy ,CommentTime )
SELECT ROW_NUMBER() OVER (ORDER BY CommentTime desc),Id,CommentText,CommentedBy ,CommentTime from comments
SELECT #TotalRecords = COUNT(Id) FROM #TempTable
SELECT * FROM #TempTable
where RowNumber > (#PageNumber - 1) * #PerPage
AND RowNumber <= #PageNumber * #PerPage
GO
Your issue is that you are getting exactly what you are asking for in SQL. When you run the stored proc the next time with the additional row inserted, that row is being factored into the results of the query.
The only way to prevent new data from affecting your paging results is to remove the new data or begin paging again from the last record of the original page.
This assumes your Id column is an incrementing value.
CREATE PROC getComments(
#PageNumber tinyint, #PerPage INT,
#LastIdFromPreviousPage INT, #TotalRecords INT OUTPUT
)
AS
BEGIN
CREATE TABLE #TempTable
(RowNumber SMALLINT, Id INT, CommentText NVARCHAR(MAX),
CommentedBy NVARCHAR(256),CommentTime DATETIME)
INSERT INTO #TempTable
(RowNumber, Id, CommentText, CommentedBy, CommentTime)
SELECT
ROW_NUMBER() OVER (ORDER BY CommentTime desc),
Id, CommentText, CommentedBy, CommentTime
FROM comments
SELECT #TotalRecords = COUNT(Id) FROM #TempTable
SELECT *
FROM #TempTable
WHERE (#LastIdFromPreviousPage IS NULL
AND RowNumber > (#PageNumber - 1) * #PerPage
AND RowNumber <= #PageNumber * #PerPage)
OR (Id < #LastIdFromPreviousPage
AND Id >= #LastIdFromPreviousPage - #PerPage)
END
GO
You could also change #LastIdFromPreviousPage to be a DATETIME of the first time you began paging and filter your results to begin paging after that date when you return the data.
Sql server 2012 introduced the OFFSET and FETCH clauses to allow an easy syntax for paging query results. I would suggest using it.
Also, I would suggest reading Aaron Bertrand's Pagination with OFFSET / FETCH : A better way article, especially of you encounter performance issues with pagination.
CREATE PROCEDURE getComments (
#PageNumber tinyint,
#PerPage INT,
#TotalRecords INT OUTPUT
)
AS
SELECT #TotalRecords = COUNT(Id) FROM comments;
SELECT Id, CommentText, CommentedBy ,CommentTime
FROM comments
ORDER BY CommentTime desc
OFFSET (#PageNumber - 1) * #PerPage ROWS
FETCH NEXT #PerPage ROWS ONLY;
GO

Alternative to SQL window functions in Sybase

I am working on Sybase Adaptive Server Enterprise (version 12.5.0.3). Trying to use Row_number() OVER (Partition by columnname order by columnname). When I execute the query it is throwing an exception saying that the syntax near OVER is incorrect. I have searched for proper row_number() syntax for sybase database, but there is nothing wrong in the syntax. I guess that the Sybase version that am using does not support row_number() OVER. I even tried dense_rank() OVER, but am getting the same error.
I need to know whether it is really a syntax issue or its because of Sybase's low version which is not supporting the key words?
If the issue is with the version, then is there any alternative for row_number OVER and dense_rank() OVER for sybase database.
My Query:
select cr.firstname, cr.lastname, cr.dob,cr.phone,
row_number() over (patition by cr.dob order by createddate) "rank"
from ff.CrossReferenceTable cr
Error Message:
Server Message: Number 156, Severity 15
Server 'MyServer', Line 1:
Incorrect syntax near the keyword 'over'.
Right, unfortunately Sybase ASE doesn't support row_number() function as well as rank() and dense_rank().
However, in some simple cases, where partition clause is not used it could be converted in the way like
select rank=identity(music), * into #new_temp_tab1 from CrossReferenceTable order by createddate
select firstname, lastname, dob, phone, rank from #new_temp_tab1
In your case it's going to be a little bit more complicated, I can recommend using cursor with temporary table to emulate row_number() over partition by behavior.
Please have a look at the example below:
create table CrossReferenceTable
(
firstname varchar(50),
lastname varchar(50),
dob int,
phone char(10),
createddate date
)
go
create proc sp_CrossReferenceTable
as
begin
declare #i int
declare #cur_firstname varchar(50)
declare #cur_lastname varchar(50)
declare #cur_dob int
declare #cur_phone varchar(10)
declare #cur_rank int
declare cur cursor for
select
cr.firstname,
cr.lastname,
cr.dob,
cr.phone,
count(*) AS "rank"
from
CrossReferenceTable cr
group by
cr.dob
order by
cr.dob,
createddate
CREATE TABLE #CrossReferenceTable_TEMP
(
firstname varchar(50),
lastname varchar(50),
dob int,
phone char(10),
rank INT
)
open cur
fetch cur into
#cur_firstname,
#cur_lastname,
#cur_dob,
#cur_phone,
#cur_rank
set #i = #cur_rank
while ##SQLSTATUS = 0
begin
if #i = 0
set #i = #cur_rank
insert into #CrossReferenceTable_TEMP
select
#cur_firstname,
#cur_lastname,
#cur_dob,
#cur_phone,
case
when #cur_rank > 1 then #cur_rank - (#i - 1)
ELSE #cur_rank
end as "rank"
set #i = #i - 1
fetch cur into
#cur_firstname,
#cur_lastname,
#cur_dob,
#cur_phone,
#cur_rank
end
select
firstname,
lastname,
dob,
phone,
rank
from
#CrossReferenceTable_TEMP
end
go
exec sp_CrossReferenceTable
Try the generic query below to have same effect as ROW_NUMBER()
SELECT
A.MyPartitionColumn,
A.MyRunningNumberColumn,
( SELECT count(*)
FROM MyTable
WHERE MyPartitionColumn = A.MyPartitionColumn
AND MyRunningNumberColumn <= A.MyRunningNumberColumn
) AS "Row_Number"
FROM MyTable A
ORDER BY MyPartitionColumn, MyRunningNumberColumn

SQL Server query with pagination and count

I want to make a database query with pagination. So, I used a common-table expression and a ranked function to achieve this. Look at the example below.
declare #table table (name varchar(30));
insert into #table values ('Jeanna Hackman');
insert into #table values ('Han Fackler');
insert into #table values ('Tiera Wetherbee');
insert into #table values ('Hilario Mccray');
insert into #table values ('Mariela Edinger');
insert into #table values ('Darla Tremble');
insert into #table values ('Mammie Cicero');
insert into #table values ('Raisa Harbour');
insert into #table values ('Nicholas Blass');
insert into #table values ('Heather Hayashi');
declare #pagenumber int = 2;
declare #pagesize int = 3;
declare #total int;
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from #table
)
select top (#pagesize) name from query
where line > (#pagenumber - 1) * #pagesize
Here, I can specify the #pagesize and #pagenumber variables to give me just the records that I want. However, this example (that comes from a stored procedure) is used to make a grid pagination in a web application. This web application requires to show the page numbers. For instance, if a have 12 records in the database and the page size is 3, then I'll have to show 4 links, each one representing a page.
But I can't do this without knowing how many records are there, and this example just gives me the subset of records.
Then I changed the stored procedure to return the count(*).
declare #pagenumber int = 2;
declare #pagesize int = 3;
declare #total int;
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line, total = count(*) over()from #table
)
select top (#pagesize) name, total from query
where line > (#pagenumber - 1) * #pagesize
So, along with each line, it will show the total number of records. But I didn't like it.
My question is if there's a better way (performance) to do this, maybe setting the #total variable without returning this information in the SELECT. Or is this total column something that won't harm the performance too much?
Thanks
Assuming you are using MSSQL 2012, you can use Offset and Fetch which cleans up server-side paging greatly. We've found performance is fine, and in most cases better. As far as getting the total column count, just use the window function below inline...it will not include the limits imposed by 'offset' and 'fetch'.
For Row_Number, you can use window functions the way you did, but I would recommend that you calculate that client side as (pagenumber*pagesize + resultsetRowNumber), so if you're on the 5th page of 10 results and on the third row you would output row 53.
When applied to an Orders table with about 2 million orders, I found the following:
FAST VERSION
This ran in under a second. The nice thing about it is that you can do your filtering in the common table expression once and it applies both to the paging process and the count. When you have many predicates in the where clause, this keeps things simple.
declare #skipRows int = 25,
#takeRows int = 100,
#count int = 0
;WITH Orders_cte AS (
SELECT OrderID
FROM dbo.Orders
)
SELECT
OrderID,
tCountOrders.CountOrders AS TotalRows
FROM Orders_cte
CROSS JOIN (SELECT Count(*) AS CountOrders FROM Orders_cte) AS tCountOrders
ORDER BY OrderID
OFFSET #skipRows ROWS
FETCH NEXT #takeRows ROWS ONLY;
SLOW VERSION
This took about 10 sec, and it was the Count(*) that caused the slowness. I'm surprised this is so slow, but I suspect it's simply calculating the total for each row. It's very clean though.
declare #skipRows int = 25,
#takeRows int = 100,
#count int = 0
SELECT
OrderID,
Count(*) Over() AS TotalRows
FROM Location.Orders
ORDER BY OrderID
OFFSET #skipRows ROWS
FETCH NEXT #takeRows ROWS ONLY;
CONCLUSION
We've gone through this performance tuning process before and actually found that it depended on the query, predicates used, and indexes involved. For instance, the second we introduced a view it chugged, so we actually query off the base table and then join up the view (which includes the base table) and it actually performs very well.
I would suggest having a couple of straight-forward strategies and applying them to high-value queries that are chugging.
DECLARE #pageNumber INT = 1 ,
#RowsPerPage INT = 20
SELECT *
FROM TableName
ORDER BY Id
OFFSET ( ( #pageNumber - 1 ) * #RowsPerPage ) ROWS
FETCH NEXT #RowsPerPage ROWS ONLY;
What if you calculate the count beforehand?
declare #pagenumber int = 2;
declare #pagesize int = 3;
declare #total int;
SELECT #total = count(*)
FROM #table
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from #table
)
select top (#pagesize) name, #total total from query
where line > (#pagenumber - 1) * #pagesize
Another way, is to calculate max(line). Check the link
Return total records from SQL Server when using ROW_NUMBER
UPD:
For single query, check marc_s's answer on the link above.
with query as
(
select name, ROW_NUMBER() OVER(ORDER BY name ASC) as line from #table
)
select top (#pagesize) name,
(SELECT MAX(line) FROM query) AS total
from query
where line > (#pagenumber - 1) * #pagesize
#pagenumber=5
#pagesize=5
Create a common table expression and write logic like this
Between ((#pagenumber-1)*(#pagesize))+1 and (#pagenumber *#pagesize)
There are many way we can achieve pagination: I hope this information is useful to you and others.
Example 1: using offset-fetch next clause. introduce in 2005
declare #table table (name varchar(30));
insert into #table values ('Jeanna Hackman');
insert into #table values ('Han Fackler');
insert into #table values ('Tiera Wetherbee');
insert into #table values ('Hilario Mccray');
insert into #table values ('Mariela Edinger');
insert into #table values ('Darla Tremble');
insert into #table values ('Mammie Cicero');
insert into #table values ('Raisa Harbour');
insert into #table values ('Nicholas Blass');
insert into #table values ('Heather Hayashi');
declare #pagenumber int = 1
declare #pagesize int = 3
--this is a CTE( common table expression and this is introduce in 2005)
with query as
(
select ROW_NUMBER() OVER(ORDER BY name ASC) as line, name from #table
)
--order by clause is required to use offset-fetch
select * from query
order by name
offset ((#pagenumber - 1) * #pagesize) rows
fetch next #pagesize rows only
Example 2: using row_number() function and between
declare #table table (name varchar(30));
insert into #table values ('Jeanna Hackman');
insert into #table values ('Han Fackler');
insert into #table values ('Tiera Wetherbee');
insert into #table values ('Hilario Mccray');
insert into #table values ('Mariela Edinger');
insert into #table values ('Darla Tremble');
insert into #table values ('Mammie Cicero');
insert into #table values ('Raisa Harbour');
insert into #table values ('Nicholas Blass');
insert into #table values ('Heather Hayashi');
declare #pagenumber int = 2
declare #pagesize int = 3
SELECT *
FROM
(select ROW_NUMBER() OVER (ORDER BY PRODUCTNAME) AS RowNum, * from Products)
as Prodcut
where RowNum between (((#pagenumber - 1) * #pageSize )+ 1)
and (#pagenumber * #pageSize )
I hope these will be helpful to all
I don't like other solutions for being too complex, so here is my version.
Execute three select queries in one go and use output parameters for getting the count values. This query returns the total count, the filter count, and the page rows. It supports sorting, searching, and filtering the source data. It's easy to read and modify.
Let's say you have two tables with one-to-many relationship, items and their prices changed over time so the example query is not too trivial.
create table shop.Items
(
Id uniqueidentifier not null primary key,
Name nvarchar(100) not null,
);
create table shop.Prices
(
ItemId uniqueidentifier not null,
Updated datetime not null,
Price money not null,
constraint PK_Prices primary key (ItemId, Updated),
constraint FK_Prices_Items foreign key (ItemId) references shop.Items(Id)
);
Here is the query:
select #TotalCount = count(*) over()
from shop.Items i;
select #FilterCount = count(*) over()
from shop.Items i
outer apply (select top 1 p.Price, p.Updated from shop.Prices p where p.ItemId = i.Id order by p.Updated desc) as p
where (#Search is null or i.Name like '%' + #Search + '%')/**where**/;
select i.Id as ItemId, i.Name, p.Price, p.Updated
from shop.Items i
outer apply (select top 1 p.Price, p.Updated from shop.Prices p where p.ItemId = i.Id order by p.Updated desc) as p
where (#Search is null or i.Name like '%' + #Search + '%')/**where**/
order by /**orderby**/i.Id
offset #SkipCount rows fetch next #TakeCount rows only;
You need to provide the following parameters to the query:
#SkipCount - how many records to skip, calculated from the page number.
#TakeCount - how many records to return, calculated from or equal to the page size.
#Search - a text to search for in some columns, provided by the grid search box.
#TotalCount - the total number of records in the data source, the output parameter.
#FilterCount - the number of records after the search and filtering operations, the output parameter.
You can replace /**orderby**/ comment with the list of columns and their ordering directions if the grid must support sorting the rows by columns. you get this info from the grid and translate it to an SQL expression. We still need to order the records by some column initially, I usually use ID column for that.
If the grid must support filtering data by each column individually, you can replace /**where**/ comment with an SQL expression for that.
If the user is not searching and filtering the data, but only clicks through the grid pages, this query doesn't change at all and the database server executes it very quickly.

SQL Server: UPDATE a table by using ORDER BY

I would like to know if there is a way to use an order by clause when updating a table. I am updating a table and setting a consecutive number, that's why the order of the update is important. Using the following sql statement, I was able to solve it without using a cursor:
DECLARE #Number INT = 0
UPDATE Test
SET #Number = Number = #Number +1
now what I'd like to to do is an order by clause like so:
DECLARE #Number INT = 0
UPDATE Test
SET #Number = Number = #Number +1
ORDER BY Test.Id DESC
I've read: How to update and order by using ms sql The solutions to this question do not solve the ordering problem - they just filter the items on which the update is applied.
Take care,
Martin
No.
Not a documented 100% supported way. There is an approach sometimes used for calculating running totals called "quirky update" that suggests that it might update in order of clustered index if certain conditions are met but as far as I know this relies completely on empirical observation rather than any guarantee.
But what version of SQL Server are you on? If SQL2005+ you might be able to do something with row_number and a CTE (You can update the CTE)
With cte As
(
SELECT id,Number,
ROW_NUMBER() OVER (ORDER BY id DESC) AS RN
FROM Test
)
UPDATE cte SET Number=RN
You can not use ORDER BY as part of the UPDATE statement (you can use in sub-selects that are part of the update).
UPDATE Test
SET Number = rowNumber
FROM Test
INNER JOIN
(SELECT ID, row_number() OVER (ORDER BY ID DESC) as rowNumber
FROM Test) drRowNumbers ON drRowNumbers.ID = Test.ID
Edit
Following solution could have problems with clustered indexes involved as mentioned here. Thanks to Martin for pointing this out.
The answer is kept to educate those (like me) who don't know all side-effects or ins and outs of SQL Server.
Expanding on the answer gaven by Quassnoi in your link, following works
DECLARE #Test TABLE (Number INTEGER, AText VARCHAR(2), ID INTEGER)
DECLARE #Number INT
INSERT INTO #Test VALUES (1, 'A', 1)
INSERT INTO #Test VALUES (2, 'B', 2)
INSERT INTO #Test VALUES (1, 'E', 5)
INSERT INTO #Test VALUES (3, 'C', 3)
INSERT INTO #Test VALUES (2, 'D', 4)
SET #Number = 0
;WITH q AS (
SELECT TOP 1000000 *
FROM #Test
ORDER BY
ID
)
UPDATE q
SET #Number = Number = #Number + 1
The row_number() function would be the best approach to this problem.
UPDATE T
SET T.Number = R.rowNum
FROM Test T
JOIN (
SELECT T2.id,row_number() over (order by T2.Id desc) rowNum from Test T2
) R on T.id=R.id
update based on Ordering by the order of values in a SQL IN() clause
Solution:
DECLARE #counter int
SET #counter = 0
;WITH q AS
(
select * from Products WHERE ID in (SELECT TOP (10) ID FROM Products WHERE ID IN( 3,2,1)
ORDER BY ID DESC)
)
update q set Display= #counter, #counter = #counter + 1
This updates based on descending 3,2,1
Hope helps someone.
I had a similar problem and solved it using ROW_NUMBER() in combination with the OVER keyword. The task was to retrospectively populate a new TicketNo (integer) field in a simple table based on the original CreatedDate, and grouped by ModuleId - so that ticket numbers started at 1 within each Module group and incremented by date. The table already had a TicketID primary key (a GUID).
Here's the SQL:
UPDATE Tickets SET TicketNo=T2.RowNo
FROM Tickets
INNER JOIN
(select TicketID, TicketNo,
ROW_NUMBER() OVER (PARTITION BY ModuleId ORDER BY DateCreated) AS RowNo from Tickets)
AS T2 ON T2.TicketID = Tickets.TicketID
Worked a treat!
I ran into the same problem and was able to resolve it in very powerful way that allows unlimited sorting possibilities.
I created a View using (saving) 2 sort orders (*explanation on how to do so below).
After that I simply applied the update queries to the View created and it worked great.
Here are the 2 queries I used on the view:
1st Query:
Update MyView
Set SortID=0
2nd Query:
DECLARE #sortID int
SET #sortID = 0
UPDATE MyView
SET #sortID = sortID = #sortID + 1
*To be able to save the sorting on the View I put TOP into the SELECT statement. This very useful workaround allows the View results to be returned sorted as set when the View was created when the View is opened. In my case it looked like:
(NOTE: Using this workaround will place an big load on the server if using a large table and it is therefore recommended to include as few fields as possible in the view if working with large tables)
SELECT TOP (600000)
dbo.Items.ID, dbo.Items.Code, dbo.Items.SortID, dbo.Supplier.Date,
dbo.Supplier.Code AS Expr1
FROM dbo.Items INNER JOIN
dbo.Supplier ON dbo.Items.SupplierCode = dbo.Supplier.Code
ORDER BY dbo.Supplier.Date, dbo.Items.ID DESC
Running: SQL Server 2005 on a Windows Server 2003
Additional Keywords: How to Update a SQL column with Ascending or Descending Numbers - Numeric Values / how to set order in SQL update statement / how to save order by in sql view / increment sql update / auto autoincrement sql update / create sql field with ascending numbers
SET #pos := 0;
UPDATE TABLE_NAME SET Roll_No = ( SELECT #pos := #pos + 1 ) ORDER BY First_Name ASC;
In the above example query simply update the student Roll_No column depending on the student Frist_Name column. From 1 to No_of_records in the table. I hope it's clear now.
IF OBJECT_ID('tempdb..#TAB') IS NOT NULL
BEGIN
DROP TABLE #TAB
END
CREATE TABLE #TAB(CH1 INT,CH2 INT,CH3 INT)
DECLARE #CH2 INT = NULL , #CH3 INT=NULL,#SPID INT=NULL,#SQL NVARCHAR(4000)='', #ParmDefinition NVARCHAR(50)= '',
#RET_MESSAGE AS VARCHAR(8000)='',#RET_ERROR INT=0
SET #ParmDefinition='#SPID INT,#CH2 INT OUTPUT,#CH3 INT OUTPUT'
SET #SQL='UPDATE T
SET CH1=#SPID,#CH2= T.CH2,#CH3= T.CH3
FROM #TAB T WITH(ROWLOCK)
INNER JOIN (
SELECT TOP(1) CH1,CH2,CH3
FROM
#TAB WITH(NOLOCK)
WHERE CH1 IS NULL
ORDER BY CH2 DESC) V ON T.CH2= V.CH2 AND T.CH3= V.CH3'
INSERT INTO #TAB
(CH2 ,CH3 )
SELECT 1,2 UNION ALL
SELECT 2,3 UNION ALL
SELECT 3,4
BEGIN TRY
WHILE EXISTS(SELECT TOP 1 1 FROM #TAB WHERE CH1 IS NULL)
BEGIN
EXECUTE #RET_ERROR = sp_executesql #SQL, #ParmDefinition,#SPID =##SPID, #CH2=#CH2 OUTPUT,#CH3=#CH3 OUTPUT;
SELECT * FROM #TAB
SELECT #CH2,#CH3
END
END TRY
BEGIN CATCH
SET #RET_ERROR=ERROR_NUMBER()
SET #RET_MESSAGE = '#ERROR_NUMBER : ' + CAST(ERROR_NUMBER() AS VARCHAR(255)) + '#ERROR_SEVERITY :' + CAST( ERROR_SEVERITY() AS VARCHAR(255))
+ '#ERROR_STATE :' + CAST(ERROR_STATE() AS VARCHAR(255)) + '#ERROR_LINE :' + CAST( ERROR_LINE() AS VARCHAR(255))
+ '#ERROR_MESSAGE :' + ERROR_MESSAGE() ;
SELECT #RET_ERROR,#RET_MESSAGE;
END CATCH

Resources