选择光标中的语句

时间:2014-08-08 11:23:21

标签: sql-server tsql

我们可以在游标中使用select查询。

示例:

CREATE PROCEDURE try  
AS  
            SET NOCOUNT ON  
Declare     @dname nvarchar(50),  
            @ename nvarchar(50),  
            @esal int


Declare curP cursor For

select d.dname,e.ename,e.sal from dept d,emp e where e.deptno=d.deptno

OPEN curP  
Fetch Next From curP Into @dname, @ename,@esal

While @@Fetch_Status = 0 Begin


select dname from curp          // this is it possible?i dont want to use print bcs i want                        to display data in tabular form  



Fetch Next From curP Into @dname,@ename,@esal

End -- End of Fetch

Close curP
Deallocate curP

3 个答案:

答案 0 :(得分:8)

如果你想用光标做到这一点:

CREATE PROCEDURE try  
AS  
            SET NOCOUNT ON  
Declare     @dname nvarchar(50)


DECLARE curP CURSOR FOR

SELECT d.dname FROM dept d

OPEN curP  
FETCH NEXT FROM curP INTO @dname

WHILE @@Fetch_Status = 0 

BEGIN

    SELECT 0 AS OrderBy, @dname , '' AS sal
    union
    SELECT 1, 
           ename , 
           CONVERT(VARCHAR,sal) AS sal
    FROM   emp
    WHERE  deptno = @dname
    ORDER BY OrderBy

    FETCH NEXT FROM curP INTO @dname

End 

Close curP
Deallocate curP

上述结果将导致:

╔══════════╦═══╗
║ Tech     ║   ║
║ Vikrant  ║ 5 ║
║ Nimesh   ║ 2 ║
╚══════════╩═══╝  
╔══════════╦═══╗
║ Creative ║   ║
║ Memo     ║ 6 ║
║ Sabir    ║ 5 ║
╚══════════╩═══╝  

还有另一种想法:

;WITH DeptsCTE AS
(
    SELECT deptno,
           dname,
           ROW_NUMBER() OVER (ORDER BY deptno) AS rn
    FROM   dept
)
SELECT dname, 
       sal
FROM   
(
    SELECT D.rn,
           0 AS drn,
           dname, 
           '' AS sal
    FROM   DeptsCTE  D
    UNION
    SELECT D.rn,
           1 AS drn,
           ename , 
           CONVERT(VARCHAR,sal) AS sal
    FROM   emp E
           JOIN DeptsCTE D
               ON D.deptno = E.deptno 
) AS T    
ORDER BY rn,drn

答案 1 :(得分:0)

是的,您可以在光标内执行select语句。

答案 2 :(得分:0)

尝试并避免使用游标。至于你的问题,是的,它会起作用,但你最终会得到多个结果集。声明一个表变量并插入该表变量,并在循环结束后从表变量中选择。请参阅下面的使用示例:

CREATE PROCEDURE usp_try
AS
BEGIN
    DECLARE @StartLoop INT
    DECLARE @EndLoop INT
    DECLARE @esal INT

    DECLARE @Result TABLE (dname NVARCHAR(50))
    DECLARE @InitResult TABLE (id INT IDENTITY(1, 1),
                         dname NVARCHAR(50),
                         ename NVARCHAR(50),
                         esal INT)

    INSERT INTO @InitResult
    SELECT ddname,
         e.ename,
         e.sal
    FROM dept AS d, emp AS e
    WHERE e.deptno = d.deptno

    SELECT @StartLoop = MIN(ID),
         @EndLoop = MAX(ID)
    FROM @InitResult

    WHILE @StartLoop <= @EndLoop
       BEGIN

          INSERT INTO @Result
          SELECT dname
          FROM @InitResult
          WHERE ID = @StartLoop

          SET @StartLoop = @StartLoop + 1
       END

    SELECT *
    FROM @Result
END