Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windowed functions can only appear in the SELECT or ORDER BY clauses-update in cursor

Tags:

sql-server

Declare @Customerid int 
DECLARE ChangeCustomerName CURSOR FOR 
select customerid from customer 
OPEN ChangeCustomerName
FETCH NEXT FROM ChangeCustomerName into @Customerid
WHILE @@fetch_status = 0
BEGIN

  update customer set customername ='Customer'
    +convert (varchar(10),ROW_NUMBER() OVER(ORDER BY customerid ASC)) 
    where customerid=@Customerid

   FETCH NEXT FROM ChangeCustomerName into @Customerid
END
close ChangeCustomerName
deallocate ChangeCustomerName

Windowed functions can only appear in the SELECT or ORDER BY clauses-update in cursor

like image 300
A.Bahrami Avatar asked Jan 29 '17 13:01

A.Bahrami


People also ask

Can you use window functions in where clause?

You can't use window functions in WHERE , because the logical order of operations in an SQL query is completely different from the SQL syntax. The logical order of operations in SQL is: FROM, JOIN. WHERE.

What are window functions used for?

What are Window Functions? Window functions enable users to perform calculations against partitions (i.e. subgroups or sections) of a result set, typically a table or the results from another query.

What are Windows function in SQL?

In SQL, a window function or analytic function is a function which uses values from one or multiple rows to return a value for each row. (This contrasts with an aggregate function, which returns a single value for multiple rows.)


1 Answers

You seem to be trying to set customer names to sequential values. For this purpose, you don't need a cursor! Just something like this:

with toupdate as (
      select c.*, row_number() over (order by customerid) as seqnum
      from customer c
     )
update toupdate
    set customername = 'Customer' + convert(varchar(10), seqnum);

You should avoid cursors whenever you can. Set-based operations are more efficient and often result in simpler code.

like image 149
Gordon Linoff Avatar answered Oct 09 '22 20:10

Gordon Linoff