Solved

Sql Server function with cursor

Posted on 2014-07-30
11
428 Views
Last Modified: 2014-08-03
Hi ,
   Can you please provide me with the equivalent Sql Server function  for  the Oracle function given below  .
     (  Note : Thru the answer to another question  in the link , I have an idea of how to write function .   But All I am really looking for is how to use cursor
                   http://www.experts-exchange.com/Database/MS-SQL-Server/Q_28486708.html
    )

   Please see the oracle query below

create or replace 
Function GetMultiObjs
(
  pParentID       IN  VARCHAR2,
  pID          IN  VARCHAR2,
  pDir       IN  VARCHAR2 DEFAULT '12'
)
  RETURN VARCHAR2 
IS 
  mRetVal    VARCHAR2(2000);

  CURSOR c1 IS
    SELECT  obj2.ObjName
    FROM    datarel rel, dataobj obj2
    WHERE Rel.uid1 = pParentID
            AND rel.uid2 = obj2.objuid
            AND rel.defuid = pID
          
  CURSOR c2 IS
    SELECT  obj2.ObjName
    FROM    datarel rel, dataobj obj2
    WHERE Rel.uid2 = pParentID
            AND rel.uid1 = obj2.objuid
            AND rel.defuid = pID
          
BEGIN
  mRetVal := '';
  BEGIN
    IF pDir = '12' THEN
      FOR rec IN c1 LOOP
          If mRetVal IS NULL Then
            mRetVal := rec.ObjName;
          ELSE
            mRetVal := mRetVal || '|' || rec.ObjName;
          END IF;
      END LOOP;
    ELSE
      FOR rec IN c2 LOOP
          If mRetVal IS NULL Then
            mRetVal := rec.ObjName;
          ELSE
            mRetVal := mRetVal || '|' || rec.ObjName;
          END IF;
      END LOOP;
    END IF;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      mRetVal := '';
    WHEN OTHERS THEN
      mRetVal := '!!!ERR!!!';
  END;

  RETURN mRetVal;
END GetMultiObjs;

Open in new window

0
Comment
Question by:Sam OZ
  • 3
  • 3
  • 2
  • +2
11 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40231124
> But All I am really looking for is how to use cursor
why would you use a cursor if that is the least efficient solution?
especially as here, it's to return a single value, which should be done with a simple select ...
0
 

Author Comment

by:Sam OZ
ID: 40231135
Hi Thanks for the reply . can you please guide me with how to  do it with cursor ? ( I don't need the whole Function - Just the  Declaration and looping thru cursor

 If you think , it can be done by a simple Query, Can you please  provide that query ?

   thanks

   Sam
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40231153
please see this article which shows the difference between cursor processing (and the general non-cursor replacement):
http://www.experts-exchange.com/Database/MS-SQL-Server/A_13640-processing-cursor-vs-temp-table-syntax.html
note: row by row processing is only needed for things where really, one row at a time needs to be "processed", and not the whole set

in your case, you don't have multiple rows to be processed, just 1 single values to be returned, hence cursor is not to be used. even in Oracle you don't need cursors for this kind of functions, just a big waste of resources.

in regards to the "simple query", I see that in the linked question you got already the answer there
0
 
LVL 33

Expert Comment

by:ste5an
ID: 40231160
Afaik, even in PL/SQL you can write that in a single, recursive statement (CTE).
0
 

Author Comment

by:Sam OZ
ID: 40231190
Hi ,
   Can you please provide me the query  ? It is different from  the previous one in just one aspect
     ( As I told before , I need only the cursor part of the query - If  simple PL/SQL  can do it , Please provide me that )

       The core logic in this is

              Loop All Rows
                   If mRetVal IS NULL Then                               --- First Row
                        mRetVal := rec.ObjName;    
                   ELSE    ---  Keep appending to RetVal with a Delim + ObjName
                       mRetVal := mRetVal || '|' || rec.ObjName;
                  END IF;
0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 142

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 100 total points
ID: 40231200
in oracle, you use listagg function:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions089.htm

in sql server, you can do this using the FOR XML subquery, see here for example
http://www.experts-exchange.com/Database/MS-SQL-Server/SQL-Server-2005/Q_28272543.html
0
 

Author Comment

by:Sam OZ
ID: 40231514
Hi Thanks for all valuable comments .  Can someone help me with the For XML query ( I am on a tight timeline and really don't have time for trial and error)  

 Can someone please give me  the For XML equivalent of just one loop

    FOR rec IN c1 LOOP
          If mRetVal IS NULL Then
            mRetVal := rec.ObjName;
          ELSE
            mRetVal := mRetVal || '|' || rec.ObjName;
          END IF;
      END LOOP;
0
 
LVL 33

Assisted Solution

by:ste5an
ste5an earned 100 total points
ID: 40231572
E.g.
DECLARE @ID INT;
DECLARE @ParentID INT;

SELECT  STUFF(( SELECT  '\' + obj2.ObjName
                FROM    datarel rel
                        INNER JOIN dataobj obj2 ON rel.uid1 = obj2.objuid
                WHERE   Rel.uid2 = @ParentID
                        AND rel.defuid = @ID
              FOR
                XML PATH('')
              ), 1, 1, '');

Open in new window


Caveat: Your Oracle solution and the above T-SQL solution guarentee no order!
0
 
LVL 48

Assisted Solution

by:PortletPaul
PortletPaul earned 150 total points
ID: 40231589
LISTAGG()

is the "equivalent"

of "FOR XML PATH" in sql server

Plus: you don't need it "for just one loop" because LISTAGG() will handle ALL the loops*

*actually it won't be loops that you use, just a simple query

    CREATE TABLE DATAOBJ
    	("OBJNAME" varchar2(8))
    ;
    
    INSERT ALL 
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('askjakja')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('aasdasd')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('asdfsfds')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('dfdfgdf')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('dfgdfg')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('dfgdfg')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('dfgdfg')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('rehtrt')
    	INTO DATAOBJ ("OBJNAME")
    		 VALUES ('dfdthrr')
    SELECT * FROM dual
    ;

Open in new window

**Query 1**:

    SELECT
           LISTAGG(OBJNAME, ' | ')
             WITHIN GROUP (ORDER BY OBJNAME) AS "Objname_list"
    FROM DATAOBJ
    

**[Results][2]**:
    
    |                                                                          OBJNAME_LIST |
    |---------------------------------------------------------------------------------------|
    | aasdasd | asdfsfds | askjakja | dfdfgdf | dfdthrr | dfgdfg | dfgdfg | dfgdfg | rehtrt |



  [1]: http://sqlfiddle.com/#!4/dd1e9/1

Open in new window

0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40231613
oops I got this wrong way around, oh well. Sorry.

But: you do not need a cursor in Oracle, and you don't need one in SQL Server either.

i.e. You can replace that Oracle cursor code with a query using listagg()
0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 150 total points
ID: 40231753
CREATE FUNCTION GetMultiObjs
--ALTER FUNCTION GetMultiObjs
(
  @pParentID  nvarchar(50),
  @pID  nvarchar(50),
  @pDir  nvarchar(50) = '12'
)
RETURNS nvarchar(max)
AS
BEGIN
SET NOCOUNT ON
DECLARE @return_value nvarchar(max)
SET @return_value = ''

SELECT @return_value = STUFF((
    SELECT '|' + obj2.ObjName
    FROM datarel rel
    INNER JOIN dataobj obj2 ON
        Rel.uid1 = @pParentID AND
        rel.uid2 = obj2.objuid AND
        rel.defuid = @pID
    ORDER BY obj2.ObjName
    FOR XML PATH('')
    ), 1, 1, '')

SELECT @return_value = @return_value + STUFF((
    SELECT '|' + obj2.ObjName
    FROM datarel rel
    INNER JOIN dataobj obj2 ON
        Rel.uid2 = @pParentID AND
        rel.uid1 = obj2.objuid AND
        rel.defuid = @pID
    ORDER BY obj2.ObjName
    FOR XML PATH('')
    ), 1, 1, '')
   
RETURN @return_value
END --FUNCTION
GO
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
From implementing a password expiration date, to datatype conversions and file export options, these are some useful settings I've found in Jasper Server.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now