Autoincrement UDT in Stored Procedure

Hi all,
I am tring to fill a UDT with a Stored Procedure.
The UDT is created in SBO.
I can't get find a way to fill the code and name columns.
Now I am trying via this Stored Procedure:
CREATE    PROCEDURE LeverFacturen
               @Datum as DateTIME= null --you can default it to null so that--if no date was passed then use today
     , @Eigens as varchar (1)
        AS
SET NOCOUNT ON
--if no date was passed in then use today's date (at 00:00:00)
if @Datum is null
     set @Datum = dateAdd(day, datediff(day,0,getdate()), 0)
        BEGIN
INSERT [@OIFLEFACT] (code,[name], U_CardCode, U_Docnum, U_LineNum,U_ItemCode,U_OIFIDGR, U_DocEntry, U_CardName, U_OIFPRRC, U_Project,U_OIFLOC)
SELECT DISTINCT (select max(code)+1 FROM  [dbo].[@OIFLEFACT]),(select max(code)+1 FROM  [dbo].[@OIFLEFACT]) as 'name', T0.cardcode,T0.DocNum,T1.LineNum, T1.ItemCode, T1.U_OIFIDGRP,T0.DocEntry,  T0.cardName, T1.U_OIFPRRC, T1.Project, T1.U_OIFLOC  
FROM ODLN T0 INNER JOIN DLN1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OINS T2 ON T0.DocNum = T2.deliveryNo 
WHERE T0.DocNum in
(SELECT DISTINCT T0.deliveryNo FROM OINS T0 WHERE ((T0.U_OIFEDRI > @Datum) OR (T0.U_OIFEDRI IS NULL)) AND T0.U_OIFSDRI < @Datum) 
AND   T1.LineNum <> (SELECT  T1.BaseLinNum FROM OSRI T0  INNER JOIN SRI1 T1 ON T0.SysSerial = T1.SysSerial
WHERE T1.ItemCode =  T2.itemCode  AND T0.IntrSerial = T2.internalSN AND T1.BaseNum = T2.deliveryNo) 
AND T1.U_OIFPRRC > 0 AND  T2.U_OIFEQST  = 1
AND T2.customer IN  ( SELECT T0.CardCode FROM OCRD T0 WHERE  T0.QryGroup19 = @Eigens)
AND T0.Comments NOT LIKE 'Periodiek%%' order by T0.cardcode,t0.DocNum,T1.LineNum, T1.ItemCode, T1.U_OIFIDGRP
end
GO
But it tells me
"Violation of PRIMARY KEY constraint 'KOIFLEFACT_PRIMARY'"
I also tried with max(code). 
Probably the table is not yet updated.
Does anybody have a hint, or solved this in another way?
Cheers,
Evert

Solved.
What I did (solution not fit for very large sets):
CREATE     PROCEDURE sp_procname
     @variable AS VARCHAR(15),
        AS
SET NOCOUNT ON
DECLARE @id INTEGER
BEGIN
DECLARE BufferCursor CURSOR FOR
SELECT XXXXXX
END
OPEN BufferCursor
   FETCH NEXT FROM BufferCursor
      INTO @U_UDFs
   WHILE (@@FETCH_STATUS=0)
BEGIN    
  BEGIN
     SET @id = (SELECT max(code) FROM [dbo].[@UDT])
  END
     IF @id = NULL
         SELECT @code=0
      ELSE
         SELECT @code = @id +1
     INSERT INTO [dbo].[@UDT](code,[name], U_UDFs,..)
                 VALUES      (@code,@code, @U_UDFs,..)
      FETCH NEXT FROM BufferCursor
     INTO @U_UDFs
END
   CLOSE BufferCursor
   DEALLOCATE BufferCursor
GO

Similar Messages

  • Unable to access Custom UDTs returned from a Java Stored Procedure

    Hi,
    I have a UDT in the DB :-
    create type contactrecord as object (
    CN_ID NUMBER(8),
    CN_TITLE VARCHAR2(40),
    CN_FIRST_NAME VARCHAR2(25)
    and this is the corresponding java class ContactDetails.java that maps to this UDT, that I loaded in the Aurora VM.
    package package1;
    mport java.sql.SQLData;
    import java.sql.SQLException;
    import java.sql.SQLInput;
    import java.sql.SQLOutput;
    public class ContactDetails implements SQLData
    private String sql_type;
    private long CN_ID;
    private String CN_TITLE;
    private String CN_FIRST_NAME;
    public String getSQLTypeName() throws SQLException
    return this.sql_type;
    //implementation of readSql
    public void readSQL(SQLInput stream, String typeName) throws SQLException
    sql_type = typeName;
    CN_ID = stream.readLong();
    CN_TITLE = stream.readString();
    CN_FIRST_NAME = stream.readString();
    public void writeSQL(SQLOutput stream) throws SQLException
    stream.writeLong(CN_ID);
    stream.writeString(CN_TITLE);
    stream.writeString(CN_FIRST_NAME);
    //getters and setters for the class vars go here.....
    There is another class A.java that has a java stored procedure/function, which I loaded into the Aurora VM
    Here is the class.
    package package1;
    public class A
    public static ContactDetails returnObject(String name )
         ContactDetails cd = new ContactDetails();
         cd.setCN_ID(1);
    cd.setCN_FIRST_NAME(name);
    return cd;
    Then I declared the call spec for A.returnObject() as
    FUNCTION returnObject(name varchar2) return contactrecord
    AS LANGUAGE JAVA
    NAME 'package1.A.returnObject(java.lang.String) return package1.ContactDetails';
    Then I tried to call the function returnObject through JDBC calls from a class in another VM.
    When I access the object returned by the function, I get a null object.
    Here is the Client code:
    CallableStatement cs = null;
    ResultSet rs = null;
    try
    cs = conn.prepareCall("{ ? = call returnObject(?) }");
    java.util.Map map = conn.getTypeMap();
    map.put("ADMIN.CONTACTRECORD", Class.forName("package1.ContactDetails"));
    conn.setTypeMap(map);
    cs.registerOutParameter(1, OracleTypes.STRUCT, "ADMIN.CONTACTRECORD");
    cs.setString(2, "John Doe" );
    cs.execute();
    ContactDetails cd = (ContactDetails)cs.getObject(1);
    System.out.println("contact first name is:-"+cd.getCN_FIRST_NAME()); //Null Pointer here..cd is null....:(
    if (cs != null) cs.close();
    catch(Exception e)
    e.printStackTrace();
    Although If I try to access the same function from a pl/sql block, I am able
    to access the contactrecord fields.
    What could be wrong ..???
    I could not find any error with the object mapping, as it works perfectly when I interact directly from my VM to the DB,
    without going thru the aurora VM.
    I am using a OCI driver to connect to the DB via JDBC.
    Thanx in advance for any help at all.
    -sk

    Shahid,
    I too have had bad luck in many cases with the automatic translation of Java types to PL/SQL and back. I think the SYS package on the PL/SQL side which handles some of the conversion is DBMS_PICKLER (there are equivalent Java classes which do the same in that world and seem to execute automagically when a conversion is needed). You might want to double-check the data type mappings against the DOC on OTN to make sure they map 1-1. Also make sure the permissions are granted against your objects to whoever is executing them, etc. Very often, I've resorted to passing simple scalar types between the two languages as in some cases the results with complex types are inconsistent.
    Sorry this isn't much help,
    -Dan
    http://www.compuware.com/products/devpartner/db/oracle_debug.htm
    Debug PL/SQL and Java in the Oracle Database

  • Retrieving a UDT object from a Java Stored Procedure

    I am really having trouble returning a UDT object (AttributeUDT) from a Java stored procedure. I am using Oracle 8.1.6 and JDeveloper 3.2.2. I have successfully used JPublisher to create the Java source code files for my UDT, now I would like to use that in coordination with my Java stored procedure. I've loaded the Java stored procedure into the database using the Deployment option in JDeveloper. However, when it loads the procedure, it translates the 3rd parameter to an OBJECT type, thus making the stored procedure invalid. I can use SQL Navigator to correct the package by changing the OBJECT reference to AttributeUDT (my UDT data type). Unfortunately, my Java stored procedure still does not work. Any help would be greatly appreciated! Thanks in advance for your time!
    In the example below, could anyone please tell me:
    1. How do I register the OUT variable for the UDT?
    2. Is it correct to use the casted call to getObject to retrieve my UDT object?
    3. Is it valid to use the UDT data type in the java stored procedure method signature?
    The call to the Java stored procedure:
    OracleCallableStatement cs3 = (OracleCallableStatement)conn.prepareCall( "{ call sandbox.getQualifiersV3( ?, ?, ?) }");
    cs3.registerOutParameter( 1, Types.VARCHAR);
    cs3.registerOutParameter( 2, Types.VARCHAR);
    cs3.registerOutParameter( 3, ???????);
    cs3.execute();
    System.out.println( "ID: " + cs3.getString( 1));
    System.out.println( "Prompt: " + cs3.getString( 2));
    AttributeUDT attributes = (AttributeUDT)cs3.getObject( 3);
    System.out.println( "Table id: " + attributes.getLogicalTableId());
    System.out.println( "Element id: " + attributes.getElementId());
    cs3.close();
    ===========================================
    The Java stored procedure:
    public static void getQualifiersV3( String ids[], String prompts[],
    AttributeUDT attributes[]) throws SQLException {
    OracleConnection conn = (OracleConnection)new OracleDriver().defaultConnection();
    Statement stmt = conn.createStatement();
    OracleResultSet rs = (OracleResultSet)stmt.executeQuery(
    "SELECT * "
    + "FROM VPS_ABOK_QUALIFIERS "
    + "WHERE qualifier_id = 2001");
    rs.next();
    ids[0] = rs.getString( 1);
    prompts[0] = rs.getString( 2);
    attributes[0] = (AttributeUDT)rs.getCustomDatum( 3, AttributeUDT.getFactory());
    rs.close();
    stmt.close();
    null

    Sounds like your C2 REF TYP1 attribute may be null. Unfortunately you neglected to say where in your code the NullPointerException occurs.

  • Calling a stored procedure which returns a UDT

    Hi devs,
    Recently I've come across this requirement where I need to get a Oracle UDT returned from a stored procedure. The stored procedure I've used is described below.
    CREATE OR REPLACE PROCEDURE test_proc(param_id IN NUMBER, cust OUT CUSTOMER)
    IS
    BEGIN
    SELECT customer INTO cust from CUS_T where id=param_id;
    END;
    the type CUSTOMER has the following structure.
    CREATE OR REPLACE TYPE CUSTOMER AS OBJECT(
    id NUMBER,
    name VARCHAR2(20)
    the table "CUS_T" is of the following structure.
    CREATE TABLE CUS_T(id NUMBER, customer CUSTOMER);
    The use case I'm trying to address is that I need to retrieve the CUSTOMER object corresponding to a particular ID through a java code snippet. Here's how I'm currently trying to get it done.
    *CallableStatement cs=connection.prapareCall("{test_proc(?,?)}");*
    *cs.setInt(1,some_int);*
    *cs.registerOutParameter(2,Types.STRUCT);*
    *cs.execute();*
    *Struct result=(Struct)cs.getObject(1);*
    Although Oracle returns UDTs as SQL Structs, I'm running into the following exception while executing the aforementioned code snippet.
    *java.sql.SQLException: ORA-03115: unsupported network datatype or representation*
    Any help on this matter would be greatly appreciated.
    Cheers,
    Prabath

    Hi,
    I've been able to find the solution for this problem. The following simple code snippet
    has the done trick.
    CallableStatement ocs = connection.prepareCall("{ call testProc(?)}");
    ocs.registerOutParameter(1, Types.STRUCT,"CUSTOMER");
    ocs.execute();
    What I did there was, simply adding the UDT_NAME (the name CUSTOMER in the
    previous example) while registering the OUT parameter.
    Cheers,
    Prabath
    Edited by: 829281 on Feb 2, 2011 5:56 PM

  • Passing UDT TABLE of VARCHAR as an Input parameter in Stored procedure call from java

    I have following Type defined at the schema: ident_arr IS TABLE OF VARCHAR2(100) which is type of one of the input parameters. I am able to create oracle.sql.ARRAY object to map it with this UDT before calling my stored procedure from java. When I execute my stored procedure, I get the following error:
    ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call to 'P_PV_WCC_INSERT'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    I have already checked all other parameter types.

    Hello,
    Thank you, guys, for advice. I should have explained calling context before, but what I basically need to do is to see if procedure(arg1, list(record(arg2, arg3))) returns true.
    I see array binding wouldn't fit there nicely. Internal procedure calls would be proc(next(arg1), next(arg2), next(arg3)) - if all these return true, external call should also return true. I would need to make a list of repeating values of arg1 and separate list(record(arg2, arg3)) into separate lists. I would also need to record whether the internal call returns true to deduce whether external call returns true.
    As I see no better way yet, I'll make Oracle procedure proc(arg1, arg2, arg3) and implement a loop in .NET side. If I optimize for performance, I'll probably pack the array of records into string and pass it for Oracle side to parse.
    Regards,
    Aurimas Pranskevicius

  • Stored Procedure to INSERT VALUE to UDT

    Hello Everyone,
          I came across a situation that I have UDT "Temp", when I enter data in AP Invoice, is there any way to exactly replicate the detail line data in to UDT, Can it be done using Transaction Notification Stored Procedure?? the UDT "Temp" have same columns as of PCH1 with same data type.
    Is it possible?? If so then please provide me the query to insert it in "Temp"..
    Which SP I have to use then?? and please provide me query..
    Thanks in advance

    Hi Idrees,
    if you Had made the UDT using SAP then please don't go for the Transaction Notification ... but if you have Created the table In Sql Server (Non-SAP Table  ) the Go for The Transaction Notification
    but if you  use UDT then "SAPbobsCOM.oUserTable" Go for It make Insert /Update/Delete Through it.
    Transaction Notification may be difficult to Handle.
      Regards,
    Mayank Shah.

  • Problem calling Stored Procedure returning SETOF UDT (Using Spring)

    I am using Spring's StoredProcedure class to call a stored procedure from a PostgreSql database. It returns a set of user defined data types. I'm having a problem in parsing the results returned.
    The user defined data type :
    CREATE TYPE process_states AS (
    process_name text,
    process_type text
    The stored procedure returns a SET of "process_state" :
    CREATE FUNTION inquire_process_state (.....)
    RETURNS SETOF process_state AS '
    SELECT ....
    I hava a Java class extending the Spring StoredProcedure classs.
    public MyProcStats extends StoredProcedure {
    private class ProcStateCallBackHandler implements RowCallBackHandler {
    public void processRow(ResultSet rs) throws SQLException {
    System.out.println(rs.getString(1));
    public MyProcStats (DataSource ds) {
    super(ds, "inquire_process_state");
    super.setFunction(true);
    declareParameter(new SqlOutparameter("rs", Types.OTHER, new ProcStateCallBackHandler());
    declareParameter(new SqlParameter("family_name", Types.VARCHAR) ;
    While testing this class, I get an errormessage
    "java.sql.SQLException:ERROR: cannot display a value of type record"
    I would appreciate if anyone can point out my mistakes. I tried declaring
    new SqlOutParameter("rs", Types.OTHER, "process_state"), but that didn't help.

    As the related posts suggest, you will need to use direct JDBC code for this.
    Also I'm not sure JDBC supports the RECORD type, so you may need to wrap your stored functions with ones that either flatten the record out, or take OBJECT types.

  • Return records from Stored Procedure to Callable Statement

    Hi All,
    I am createing a web application to display a students score card.
    I have written a stored procedure in oracle that accepts the student roll number as input and returns a set of records as output containing the students scoring back to the JSP page where it has to be put into a table format.
    how do i register the output type of "records" from the stored function in oracle in the "registerOutParameter" method of the "callable" statement in the JSP page.
    if not by this way is there any method using which a "stored function/procedure" returning "record(s)" to the jsp page called using "callable" statement be retrieved to be used in the page. let me know any method other that writing a query for the database in the JSP page itself.

    I have a question for you:
    If the stored procedure is doing nothing more than generating a set of results why are you even using one?
    You could create a view or write a simple query like you mentioned.
    If you're intent on going the stored procedure route, then I have a suggestion. Part of the JDBC 2.0 spec allows you to basically return an object from a CallableStatement. Its a little involved but can be done. An article that I ran across a while back really helped me to figure out how to do this. There URL to it is as follows:
    http://www.fawcette.com/archives/premier/mgznarch/javapro/2000/03mar00/bs0003/bs0003.asp
    Pay close attention to the last section of the article: Persistence of Structured Types.
    Here's some important snippets of code:
    String UDT_NAME = "SCHEMA_NAME.PRODUCT_TYPE_OBJ";
    cstmt.setLong(1, value1);
    cstmt.setLong(2, value2);
    cstmt.setLong(3, value3);
    // By updating the type map in the connection object
    // the Driver will be able to convert the array being returned
    // into an array of LikeProductsInfo[] objects.
    java.util.Map map = cstmt.getConnection().getTypeMap();
    map.put(UDT_NAME, ProductTypeObject.class);
    super.cstmt.registerOutParameter(4, java.sql.Types.STRUCT, UDT_NAME);
    * This is the class that is being mapped to the oracle object. 
    * There are two methods in the SQLData interface.
    public class ProductTypeObject implements java.sql.SQLData, java.io.Serializable
        * Implementation of method declared in the SQLData interface.  This method
        * is called by the JDBC driver when mapping the UDT, SCHEMA_NAME.Product_Type_Obj,
        * to this class.
        * The object being returned contains a slew of objects defined as tables,
        * these are retrieved as java.sql.Array objects.
         public void readSQL(SQLInput stream, String typeName) throws SQLException
            String[] value1 = (String[])stream.readArray().getArray();
            String[] value2 = (String[])stream.readArray().getArray();
         public void writeSQL(SQLOutput stream) throws SQLException
    }You'll also need to create Oracles Object. The specification for mine follows:
    TYPE Detail_Type IS TABLE OF VARCHAR2(1024);
    TYPE Product_Type_Obj AS OBJECT (
      value1  Detail_Type,
      value2 Detail_Type,
      value3 Detail_Type,
      value4 Detail_Type,
      value5 Detail_Type,
      value6 Detail_Type,
      value7 Detail_Type,
      value8 Detail_Type);Hope this helps,
    Zac

  • Stored Procedure for custom permission check

    Hi,
    I have created 2 UDTs for Master Data and Master Rows, and generated a UDO form for this.
    Only few users can add master data, but all users should be able to update fields in the rows for existing master records (but not the fields in the header).
    For this, I can probably add a custom permission UDF in User Master.
    But how can I code the Stored Procedure based on this UDF in the User Master, and whether rows are modified for existing records?
    Thanks.

    John......
    Try this.....
    IF (@object_type = '140' And (Select ObjType From OPDF
           Where DocEntry = @list_of_cols_val_tab_del)='46'
    AND @transaction_type IN ('A'))
    BEGIN
    if exists(select t0.DocEntry from OPDF T0 inner join PDF4 T1 on
    T0.DocNum = T1.DocNum where t1.ObjType ='46' AND (T0.Series = '15' AND T1.OcrCode != 'U-1')
    and T0.DocEntry = @list_of_cols_val_tab_del)
    begin
    select @error = 1,
    @error_message = 'Check Unit'
    end
    End
    Above SP will only work when your Series Code is 15 and OcrCode is not equal to 'U-1'....
    Please confirm........
    And Object type for Payment Draft 140 is right.....
    Regards,
    Rahul

  • Stored Procedure for @Table

    Dear Friends,
    Greetings...
    I am trying to write a stored procedure on a No Object UDT. I am having difficulty in getting the Object Type for it.
    I read in the forum that it can done by using Object_Type = "-3@TableName", but it did not help.
    In the SDK help it says use Object_Type = 153 for UDT , but i have no luck so far.
    Kindly Help.
    Regards
    John

    Hi JohnSmith@B1,
    you try  "-3 @tablename". you must sure it have space between -3 and @tablename.
    thanks,
    H2

  • Calling Stored Procedure w/JPublisher generated classes

    Hi,
    We are trying to pass Oracle nested tables as input/output parameters to several of our stored procedures to support bulk binding operations in the database from our applications. We have some database defined types and stored procedures that use these as input/output parameters which have been tested and working at the database level. I managed to get JPublisher to create these classes and compile fine, but I am not sure exactly how to register these classes as parameters with the stored procedure Java call. Any assistance is appreciated.
    Here is a sample of the db types/procedures:
    TYPE USER_APP_TYPE IS OBJECT
        User_ID             VARCHAR2(50), -- input fields
        App_ID              VARCHAR2(50),
        App_Type            VARCHAR2(50),
        App_Obj_ID          VARCHAR2(50),
        Status              VARCHAR2(30),   -- output fields
        Desc_String         VARCHAR2(255),
        Comments            VARCHAR2(255)
    TYPE USER_APP_LIST IS TABLE OF USER_APP_TYPE;
    CREATE OR REPLACE
    PACKAGE BODY PKG_MOD_BULK
    AS
        PROCEDURE LOOKUPAPPBYUSER_BULK(
            p_InOutRS   IN OUT  USER_APP_LIST)
        IS
            BEGIN
            ... do work - fill in output fields ...
            END LOOKUPAPPBYUSER_BULK;
    END PKG_MOD_BULK;So using JPublisher 3 classes were generated with constructors and getter/setter methods:
    UserAppType.java
    UserAppTypeRef.java
    UserAppList.java
    My consumer POC code looks like this:
    public class BulkBindingDemo
        @SuppressWarnings("CallToThreadDumpStack")
        public static void main(String[] args) 
            Connection conn = null;
            try
                String UserName = "user";
                String Password = "pass";
                // Load JDBC driver
                Class.forName("oracle.jdbc.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@mydatabse.com:1521:mysid", UserName, Password);           
                // Create instances of custom database UDT classes.
                UserAppList myAppList = new UserAppLicList();
                UserAppType[] myAppArr = new UserAppType[2];
                // Populate UDTs          
                myAppArr[0] = new UserAppType("bob" ,"acct","fiscal","1FG452ABC",null,null,null,null,null,null,null);
                myAppArr[1] = new UserAppType("joe","hr","benefits","89JTYG671",null,null,null,null,null,null,null);
                myAppList.setArray(myAppArr);                                               
                // Not sure how to set parameter as input/output.
                CallableStatement cs = conn.prepareCall("BEGIN MY_SCHEMA.PKG_MOD_BULK.LOOKUPAPPBYUSER_BULK(?); END;");
                cs.setObject("p_InOutRs", myAppLicList);
                cs.execute();
                ResultSet rs = cs.getResultSet();
                // Get results - null fields from above should be populated
                if (rs.first())
                    myAppList = (UserAppList)rs.getObject("p_InOutRs");
                    myAppArr = myAppList.getArray();
                    System.out.println("status:   " + myAppArr[0].getStatus());
                    System.out.println("desc str: " + myAppArr[0].getDescString());
                    System.out.println("comments: " + myAppArr[0].getComments());
                    // additional fields here..
                //MyObject[] myObjectAry = (MyObject[])p_myObjectArray.getArray();
                //cs.registerOutParameter(1,Types.CHAR);                      
            catch (Exception e)
                e.printStackTrace();
            finally
                if (conn != null)
                try { conn.close(); }
                catch (Exception e) {}
    }So this code will compile and run up to the stored procedure call itself, but I'm not sure how to set the parameters for in/out with these generated classes. Any ideas?

    Anyone? Still haven't figured this one out...

  • Stored Procedure to create table for PdO Change Log

    Hi Experts,
    I have read in the forums that the only way to get a Change Log was to create a Stored Prodedure and create a new Table that is populated with the Change when ever a User update a Production Order.
    I started on this Stored Procedure and have hit a wall on a error. I'm fairly new to queries...
    Here is what I have so far:
    if((@transaction_type = 'U')and(@object_type = '202'))
    BEGIN
    set @PdO = case @object_type
              INSERT INTO ChangeLogPdO2 (DocEntry, Status, ItemCode, PlannedQty, DueDate)
              SELECT T0.DocEntry, T0.Status, T0.ItemCode, T0.PlannedQty, T0.DueDate
              FROM OWOR T0      
              WHERE T0.DocEntry = @list_of_cols_val_tab_del
        END
    if(@PdO = 'true')
    begin
          select @error = 1
          select @error_message = N'My Error message'
    end
    I plan to add more columns, but only started with these. Also how do I put a time stamp on this?
    Thanks,
    Marli
    Edited by: Marli Schutte on Feb 3, 2010 7:09 PM

    Gordon,
    I created a new UDT named CLPdO.
    Then I did as you suggested and I get the error message 'Incorrect syntax near the keyword 'INSERT''.
    Here is how the Sotred Procedure now look:
    [code}
    if((@transaction_type = 'U')and(@object_type = '202'))
    BEGIN
    set @PdO = case @object_type
              INSERT INTO dbo@CLPdO (DocEntry, Status, ItemCode, PlannedQty, DueDate)
              SELECT T0.DocEntry, T0.Status, T0.ItemCode, T0.PlannedQty, T0.DueDate
              FROM OWOR T0      
              WHERE T0.DocEntry = @list_of_cols_val_tab_del
        END
    if(@PdO = 'true')
    begin
          select @error = 1
          select @error_message = N'My Error message'
    end
    Any help will be appreciated.
    Marli

  • Get variable values from a stored procedure

    I am using SQL 2008R2 and I want to replace a view inside a stored procedure with a new stored procedure to return multiple variable values. Currently I am using the code below to get values for 4 different variables.  I would rather get the 4 variables
    from a stored procedure (which returns all of these 4 values and more) but not sure how to do so.  Below is the code for getting the 4 variable values in my current sp.
    DECLARE @TotalCarb real;
    DECLARE @TotalPro real;
    DECLARE @TotalFat real;
    DECLARE @TotalLiquid real;
    SELECT @TotalCarb = ISNULL(TotCarb,0),
    @TotalPro = ISNULL(TotPro,0),
    @TotalFat = ISNULL(TotFat,0),
    @TotalLiquid = ISNULL(TotLiq,0)
    FROM dbo.vw_ActualFoodTotals
    WHERE (MealID = @MealID);

    You can replace the view with inline table valued user-defined function:
    http://www.sqlusa.com/bestpractices/training/scripts/userdefinedfunction/
    See example: SQL create  INLINE table-valued function like a parametrized view
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Pointbase : How can I create a stored procedure with Pointbase database?

    Hello,
    Excuse me for my english, I'm not anglophone. I try to create a stored procedure.
    This is my file SampleExternalMethods.java :
      import java.sql.*;    //import com.pointbase.jdbc.jdbcInOutDoubleWrapper;          public class SampleExternalMethods    {      // A connection object to allow database callback      static Connection conn = null;      static Statement l_stmt;      static Statement m_stmt;      static CallableStatement m_callStmt = null;      static ResultSet l_rs = null;          public static void main(String[] args)      {        try        {          String url = "jdbc:pointbase:server://localhost/pointbaseDB";          String username = "PBPUBLIC";          String password = "PBPUBLIC";          conn = DriverManager.getConnection(url, username, password);          doCreateProcedure();          doInvokeProcedure();        } catch (SQLException e) {          e.printStackTrace();        } finally {          if (m_stmt != null) {            try {              m_stmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (m_callStmt != null) {            try {              m_callStmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (conn != null) {            try {              conn.close();            } catch (Exception e) {              e.printStackTrace();            }          }        }      }                  public static void getCountry(String Iso_Code)      {        try        {          // Query the database for the country iso code          l_stmt = conn.createStatement();          l_rs = l_stmt.executeQuery( "SELECT * FROM countries"          + " WHERE country_iso_code ='" + Iso_Code + "'");          //Affichage du résultat de la requête          l_rs.next();          System.out.print(l_rs.getString(1) + " - ");          System.out.print(l_rs.getString(2) + " - ");          System.out.println(l_rs.getString(3));          // Close the result set          l_rs.close();        } catch (SQLException e) {          e.printStackTrace();        } finally {          if (l_rs != null) {            try {              l_rs.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (l_stmt != null) {            try {              l_stmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }        }      }            public static void doCreateProcedure() throws SQLException {        // SQL statement to create a stored procedure        String SQL_CREATE_PROC = "CREATE PROCEDURE getCountry(IN P1 VARCHAR(30))"        + " LANGUAGE JAVA"        + " SPECIFIC getCountry"        + " NO SQL"        + " EXTERNAL NAME \"SampleExternalMethods::getCountry\""        + " PARAMETER STYLE SQL";        // Create a SQL statement        m_stmt = conn.createStatement();        // Execute the SQL        m_stmt.executeUpdate(SQL_CREATE_PROC);        // Close the statement        //m_stmt.close();      }          public static void doInvokeProcedure() throws SQLException {        // Create SQL to invoke stored procedures        String SQL_USE_PROC = "{ call getCountry(?) }";        // Create a callable statement with three binding parameters        m_callStmt = conn.prepareCall(SQL_USE_PROC);        m_callStmt.setString(1, "CA");        m_callStmt.executeQuery();        // Close the callable statement        //m_callStmt.close();      }    } 
    Afterwards, I have read this note in a Pointbase document:
    To invoke the dateConvert external Java method from a stored function, you must use the
    CREATE FUNCTION statement. The dateConvert external Java method is called from the
    class, SampleExternalMethods.
    In order for the database to access this external Java method, the class SampleExternalMethods
    must be included in the database CLASSPATH. For PointBase Embedded - Server Option, it
    must be in the Server CLASSPATH, but not in the Client CLASSPATH.
    If PointBase Server is run with the Java Security Manager, in the java policy file grant
    ’com.pointbase.sp.spPermission’ to the class that implements the external Java method.
    An "spPermission" consists of a class name with no action. The class name is a name of a class
    that could be used in creating a Stored Procedure in PointBase. The naming convention follows
    the hierarchical property naming convention and that is supported by
    "java.security.BasicPermission". An asterisk may appear by itself, or if immediately preceded
    by ".", may appear at the end of the name, to signify a wildcard match. The name cannot
    contain any white spaces.
    I'm not sure, but I suppose that I must include the class SampleExternalMethods in a .jar file.
    The database CLASSPATH could be : C:\Sun\AppServer\pointbase\lib\
    These my files in this database CLASSPATH:
    pbclient.jar
    pbembedded.jar
    pbtools.jar
    pbupgrade.jar
    I have tryed to include the class SampleExternalMethods in pbclient.jar and pbembedded.jar with this command:
    jar -uf pbembedded.jar SampleExternalMethods
    Afterwards I do that,
    1) Start Pointbase
    2) Configuration of classpath
    set classpath=C:\Sun\AppServer\pointbase\lib\pbclient.jar
    set classpath=%classpath%;D:\J2EE\Ch07Code\Ch07_06
    I precise that my file SampleExternalMethods is into D:\J2EE\Ch07Code\Ch07_06\Ch07.
    Then, I run the program:
    D:\J2EE\Ch07Code\Ch07_06>java -Djdbc.drivers=com.pointbase.jdbc.jdbcUniversalDriver Ch07.SampleExternalMethods
    But I have an error message:
    Exception in thread "main" java.lang.NoClassDefFoundError: Ch07.SampleExternalMethods (wrong name: SampleExternalMethods)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.DefineClass(ClassLoader.java:539)
    The problem, I suppose, comes from that the class SampleExternalMethods
    must be included in the database CLASSPATH, but there is a pbserver.jar with pointbase normally, but I didn't find it. That's why I use pbembedded.jar or pbclient.jar in order to include the class SampleExternalMethods. May be I must start from C:\Sun\AppServer\pointbase\lib\ instead of D:\J2EE\Ch07Code\Ch07_06\Ch07?
    Please, can somebody helps me?
    Thank you in advance.
    cagou!

    jschell wrote:
    And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    >And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    >
    And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    Thank you for your response, I have done two classes:
    SampleExternalMethods.java:
    package Ch07;
    import java.sql.*;*
    *public class SampleExternalMethods*
    *public static void getCountry(String Iso_Code)*
    *// A connection object to allow database callback*
    *Connection l_conn = null;*
    *Statement l_stmt = null;*
    *ResultSet l_rs = null;*
    *try*
    *String url = "jdbc:pointbase:server://localhost/pointbaseDB";*
    *String username = "PBPUBLIC";*
    *String password = "PBPUBLIC";*
    *l_conn = DriverManager.getConnection(url, username, password);*
    *// Query the database for the country iso code*
    *l_stmt = l_conn.createStatement();*
    *l_rs = l_stmt.executeQuery( "SELECT* FROM PBPUBLIC.COUNTRIES"
    +" WHERE country_iso_code ='"+ Iso_Code +"'");+
    +//Affichage du r&eacute;sultat de la requ&ecirc;te+
    +l_rs.next();+
    +System.out.print(l_rs.getString(1)+ " - ");
    System.out.print(l_rs.getString(2) +" - ");+
    +System.out.println(l_rs.getString(3));+
    +// Close the result set+
    +l_rs.close();+
    +} catch (SQLException e) {+
    +e.printStackTrace();+
    +} finally {+
    +if (l_rs != null) {+
    +try {+
    +l_rs.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (l_stmt != null) {+
    +try {+
    +l_stmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (l_conn != null) {+
    +try {+
    +l_conn.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +}+
    +}+
    +}+
    CreateMethods.java:
    +package Ch07;+
    +import java.sql.*;+
    +public class CreateMethods+
    +{+
    +// A connection object to allow database callback+
    +static Connection m_conn = null;+
    +static Statement m_stmt;+
    +static CallableStatement m_callStmt = null;+
    +public static void main(String[] args)+
    +{+
    +try+
    +{+
    +String url = "jdbc:pointbase:server://localhost/pointbaseDB";+
    +String username = "PBPUBLIC";+
    +String password = "PBPUBLIC";+
    +m_conn = DriverManager.getConnection(url, username, password);+
    +doCreateProcedure();+
    +doInvokeProcedure();+
    +} catch (SQLException e) {+
    +e.printStackTrace();+
    +} finally {+
    +if (m_stmt != null) {+
    +try {+
    +m_stmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (m_callStmt != null) {+
    +try {+
    +m_callStmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (m_conn != null) {+
    +try {+
    +m_conn.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +}+
    +}+
    +public static void doCreateProcedure() throws SQLException {+
    +// SQL statement to create a stored procedure+
    +String SQL_CREATE_PROC = "CREATE PROCEDURE PBPUBLIC.getCountry(IN P1 VARCHAR(30))"+
    " LANGUAGE JAVA"
    +" SPECIFIC getCountry"+
    " NO SQL"
    +" EXTERNAL NAME \"SampleExternalMethods::getCountry\""+
    " PARAMETER STYLE SQL";
    // Create a SQL statement
    m_stmt = m_conn.createStatement();
    // Execute the SQL
    m_stmt.executeUpdate(SQL_CREATE_PROC);
    // Close the statement
    //m_stmt.close();
    public static void doInvokeProcedure() throws SQLException {
    // Create SQL to invoke stored procedures
    String SQL_USE_PROC = "{ call getCountry(?) }";
    // Create a callable statement with three binding parameters
    m_callStmt = m_conn.prepareCall(SQL_USE_PROC);
    m_callStmt.setString(2, "CA");
    m_callStmt.executeQuery();
    // Close the callable statement
    //m_callStmt.close();
    }But I have the same error message that previously.
    I have read this note and I suppose that the problem is linked:
    If PointBase Server is run with the Java Security Manager, in the java policy file grant
    *’com.pointbase.sp.spPermission’ to the class that implements the external Java method.*
    An "spPermission" consists of a class name with no action. The class name is a name of a class
    that could be used in creating a Stored Procedure in PointBase. The naming convention follows
    the hierarchical property naming convention and that is supported by
    *"java.security.BasicPermission". An asterisk may appear by itself, or if immediately preceded*
    by ".", may appear at the end of the name, to signify a wildcard match. The name cannot
    contain any white spaces.
    Can you explain me what I must to do in order to solve this problem of spPermission.
    Thanks.

  • How to view the returned data from a stored procedure in TOAD?

    Hi,
    I created ref cursor in the stored procedure to return data. The stored procedure works fine, just want to view the result in TOAD. The BEGIN... EXEC... END can execute the stored procedure, but how to make the result display?
    Thanks!

    Right click the editor and choose
    "Prompt For Substitution Variables".
    Run for example the following code:
    DECLARE
    PROCEDURE p (cur OUT sys_refcursor)
    AS
    BEGIN
    OPEN cur FOR
    SELECT *
    FROM DUAL;
    END p;
    BEGIN
    p (:cur);
    END;
    The result will display in Toad's Data Grid!
    Regards Michael

Maybe you are looking for