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
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? 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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With