Search code examples
sqlsql-servercursor

How can I replace a cursor in sql server for printing an output


I want to know how to replace a cursor in SQL Server because it performs badly. I tried using a CTE for list recursively but I don't know how to output the columns. I want to print it because I want paste the output in a .txt file.

This is the CTE so far:

WITH EmpleadosRec (EmpNombre,EmpID) 
AS
(
    SELECT[First Name],ID from employees where id=1
    UNION ALL
    select e.[First Name], ID+1 from employees as e
    INNER JOIN EmpleadosRec er
    ON e.id = er.EmpID 
    WHERE e.id < 5
)
select *
from EmpleadosRec

Solution

  • DECLARE @id int = 1
    DECLARE @FirstName varchar(50)
    
    WHILE @id < 5
    BEGIN
        SELECT @FirstName = [First Name] from employees where id = @id 
    
        Print '@FirstName = ' + @FirstName + ' @id = ' + CAST(@id as varchar(50))
        SET @id = @id + 1
    END
    GO
    

    But this method is bad if you process a large number of rows.

    In this case check MSDN bcp Utility

    bcp "SELECT FirstName, LastName FROM AdventureWorks2012.Person.Person ORDER BY LastName, Firstname" queryout Contacts.txt -c -T
    

    Also in SQL Management Studio Menu Query -> Results To -> Results To File