Can we use select query within cursor.
Example:
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
Yes, you can do select statements inside the cursor.
Cursor using WITH clause as follows : CURSOR c_API_MSG IS WITH SAMI AS (SELECT * FROM NAGENDRA WHERE STATUS = 'NEW') SELECT * FROM SAMI WHERE ROWNUM <= TO_NUMBER (10);
Syntax: DECLARE CURSOR <cursor_name> IS <SELECT statement>; BEGIN FOR I IN <cursor_name> LOOP . . END LOOP; END; In the above syntax, the declaration part contains the declaration of the cursor.
If you want to do it with a cursor:
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
The above will result to :
╔══════════╦═══╗
║ Tech ║ ║
║ Vikrant ║ 5 ║
║ Nimesh ║ 2 ║
╚══════════╩═══╝
╔══════════╦═══╗
║ Creative ║ ║
║ Memo ║ 6 ║
║ Sabir ║ 5 ║
╚══════════╩═══╝
There would be another way thought:
;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
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