如何替换sql server中的游标以打印输出

时间:2013-12-13 14:16:12

标签: sql sql-server cursor

我想知道如何替换SQL Server中的游标,因为它执行得很糟糕。我尝试递归使用CTE列表,但我不知道如何输出列。我想打印它,因为我想将输出粘贴到.txt文件中。

到目前为止这是CTE:

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

1 个答案:

答案 0 :(得分:1)

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

但是如果你处理大量的行,这个方法就不好了。

在这种情况下,请检查MSDN bcp Utility

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

同样在SQL Management Studio中 菜单查询 - &gt;结果 - >结果归档