Working with Cursor in SQL Server

cursor sql server

Cursors are mechanisms that allow the rows of a table to be manipulated one by one. They act as pointers that point to the lines that form the result of a given query that is stored in the courses. We can retrieve and manipulate the values of each line pointed by a course.

See below the syntax for creating a cursor in SQL Server

--drop table customer_table --go --create table customer_table( --customer_name varchar(200), --customer_cpf varchar(200) --) --go --insert into customer_table values --('Fabio', NULL) , --('Jorge', 21325658454) --go --select * from customer_table --go DECLARE @customer_name VARCHAR(50), @cpf_customer VARCHAR(50) --Declaring the cursor DECLARE cursor_name CURSOR FOR --data that o courses will work SELECT customer_name, cpf_customer FROM customer_table --open cursor OPEN cursor_name --position cursor pointer on first row of the above select result FETCH NEXT FROM cursor_name --inserts the values of the first row of the result stored in the cursor in the variables INTO @client_name, @cpf_cliente --This part says "While there is a line in the cursor, do:" WHILE @@FETCH_STATUS = 0 --In this part you insert the block of instructions that will work on your cursor. --If CPF is null BEGIN IF ((SELECT cpf_customer FROM customer_table WHERE cpf_customer = @cpf_customer) is NULL) --Insert the text "Update CPF" BEGIN UPDATE table_customers SET customer_name = @customer_name at the end of the person's name Update CPF' END FETCH NEXT FROM cursor_name INTO @client_name, @cpf_client END --To close the course you need to enter the following commands CLOSE cursor_name DEALLOCATE cursor_name select * from client_table go

Watch a video on Creating a Cursor

You can use Cursor for any number of situations.

If you want to see more about cursors go to:

 812 Total Visualizações,  11 Visualizações Hoje

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.