Retrive a new sequence value from a table using Stored Procedure

Dear experts
i have written the following stored procedure, but i want this to return itemid to the environment. Please help as i am absolutely new to oracle.
create or replace procedure "SP_ITEMS"
(vitem IN VARCHAR2,
vqty IN NUMBER,
vrate IN NUMBER)
is
begin
INSERT INTO ITEMS (item,qty,rate)
VALUES (vitem,vqty,vrate);
end;
Thanks
With regards
Manish Sawjiani

If you want a column to be automatically populated with a sequence, then you need to create a sequence, and create a trigger to populate the column with the sequence. You can use the returning clause in a select statement to return the value of the inserted sequence. You can do this with just sql or you can put it in a procedure. I have demonstrated both below. This is a general sql and pl/sql problem, not something specific to the Express Edition, so please post future such questions in the sql and pl/sql discussion group instead.
SCOTT@10gXE> CREATE TABLE items
  2    (itemid NUMBER,
  3       item   VARCHAR2 (50),
  4       qty    NUMBER (10, 3),
  5       rate   NUMBER (10, 3))
  6  /
Table created.
SCOTT@10gXE> CREATE SEQUENCE item_sequence
  2  /
Sequence created.
SCOTT@10gXE> CREATE OR REPLACE TRIGGER items_bir
  2    BEFORE INSERT ON items
  3    FOR EACH ROW
  4  BEGIN
  5    SELECT item_sequence.NEXTVAL
  6    INTO   :NEW.itemid
  7    FROM   DUAL;
  8  END items_bir;
  9  /
Trigger created.
SCOTT@10gXE> SHOW ERRORS
No errors.
SCOTT@10gXE> VARIABLE g_itemid NUMBER
SCOTT@10gXE> INSERT INTO items (item, qty, rate)
  2  VALUES ('item1', 2, 3)
  3  RETURNING itemid INTO :g_itemid
  4  /
1 row created.
SCOTT@10gXE> PRINT g_itemid
  G_ITEMID
         1
SCOTT@10gXE> CREATE OR REPLACE PROCEDURE sp_items
  2    (p_item      IN  VARCHAR2,
  3       p_qty      IN  NUMBER,
  4       p_rate      IN  NUMBER,
  5       p_itemid OUT NUMBER)
  6  AS
  7  BEGIN
  8    INSERT INTO ITEMS (item, qty, rate)
  9    VALUES (p_item, p_qty, p_rate)
10    RETURNING itemid INTO p_itemid;
11  END sp_items;
12  /
Procedure created.
SCOTT@10gXE> SHOW ERRORS
No errors.
SCOTT@10gXE> EXECUTE sp_items ('item2', 3, 4, :g_itemid)
PL/SQL procedure successfully completed.
SCOTT@10gXE> PRINT g_itemid
  G_ITEMID
         2
SCOTT@10gXE> SELECT * FROM items
  2  /
    ITEMID ITEM                                                      QTY       RATE
         1 item1                                                       2          3
         2 item2                                                       3          4
2 rows selected.
SCOTT@10gXE>

Similar Messages

  • Retrive the second-highest value from the table using query.

    Hi,
    I am using Oracle 8i...
    I have to retrieve the second-highest salary from the table...for this I need to write a SQL..Can anybody please help me to figure out this problem..Thanks in advance..
    smitha

    Using analytic functions
    SELECT *
    FROM (SELECT other_columns,DENSE_RANK() OVER(ORDER BY salary DESC) sal_rank
          FROM table)
    WHERE sal_rank = 2
    Using Order by and rownum
    SELECT *
    FROM (SELECT other_columns,rownum sal_rank
          FROM (SELECT other_columns,salary
                FROM table
                ORDER BY salary DESC))
    WHERE sal_rank = 2TTFN
    John

  • How to get string value from database table using Visual Studio 2005?

    Hi,
    Im developing plugin in illustrator cs3 using visual studio 2005. I need to get the values eneterd in database. Im able to get the integer values. But while getting string values it is returning empty value.
    Im using the below code to get the values from database table
    bool Table::Get(char* FieldName,int& FieldValue)
        try
            _variant_t  vtValue;
            vtValue = m_Rec->Fields->GetItem(FieldName)->GetValue();
            FieldValue=vtValue.intVal;
        CATCHERRGET
        sprintf(m_ErrStr,"Success");
        return 1;
    Im using the below code to get the values.
    AIErr getProjects()
        char buf[5000];
        int i;   
        std::string  catName;
        ::CoInitialize(NULL);
        Database db;
        Table tbl;
        errno_t err;
        err = fopen(&file,"c:\\DBResult.txt","w");
        fprintf(file, "Before Connection Established\n");
        //MessageBox(NULL,CnnStr,"Connection String",0);
        if(!db.Open(g->username,g->password,CnnStr))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        fprintf(file, "After Connection Established\n");
    if(!db.Execute("select ProjectID,ProjectName from projectsample",tbl))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        int ProjectID;
        int UserID;
        int ProjectTitle;
        char ProjectName[ProjectNameSize];
        if(!tbl.ISEOF())
            tbl.MoveFirst();
        ProjectArrCnt=0;
        for(i=0;i<128;i++)
            buf[i]='\0';
            int j=0;
        while(!tbl.ISEOF())
            if(tbl.Get("ProjectID",ProjectID))
                fprintf(file,"Project ID: %d ",ProjectID);
                ProjectInfo[ProjectArrCnt].ProjectID = ProjectID;
                sprintf(buf,"%d",ProjectID);
                //MessageBox(NULL, buf,"f ID", 0);
                j++;
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            //if(tbl.Get("ProjectTitle",ProjectName))
            if(tbl.Get("ProjectName",ProjectName))
                MessageBox(NULL,"Inside","",0);
                fprintf(file,"ProjectTitle: %s\n",ProjectName);
                //catName=CategoryName;
                ProjectInfo[ProjectArrCnt].ProjectName=ProjectName;
                //sprintf(buf,"%s",ProjectName);
                MessageBox(NULL,(LPCSTR)ProjectName,"",0);
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            ProjectArrCnt++;
            //MessageBox(NULL, "While", "WIN API Test",0);
            tbl.MoveNext();
        //MessageBox(NULL, ProjectInfo[i].ProjectName.c_str(),"f Name", 0);
        ::CoUninitialize();
        //sprintf(buf,"%s",file);
        //MessageBox(NULL,buf,"File",0);
        fprintf(file, "Connection closed\n");
        fclose(file);
        for(i=0;i<ProjectArrCnt;i++)
            sprintf(buf,"%i",ProjectInfo[i].ProjectID);
            //MessageBox(NULL,buf,"Proj ID",0);
            //MessageBox(NULL,ProjectInfo[i].ProjectName.c_str(),"Project Name",0);
        return 0;
    In the above code im geeting project D which is an integer value. But not able to get the project name.
    Please some one guide me.

    As I said in the other thread, this really isn't the place to ask questions about a database API unrelated to the Illustrator SDK. You're far more like to find people familliar with your problem on a forum that is dedicated to answering those kinds of questions instead.

  • When inserting 2 column details in a single table using Stored Procedure.Only 2 Column details getting inserted.1column details are not getting into the table.Please see the below script and help me to change.

    Line 390 Under the (Insert into SALES_TRADEIN Table)
    I need to insert (TradeIn_1_VIN) Values If there is no values in (TradeIn_1_VIN) then i have to insert (TradeIn_2_VIN) values to the (SALES_TRADEIN) Table.
    After i run then below script only (TradeIn_2_VIN) values are get inserted in the table. (TradeIn_1_VIN) are not getting loaded in to the table.
    I think there is the problem from Line No (404 to 414) Please help me change those particular lines to insert (TradeIn_1_VIN) Values also.If there is no details then (TradeIn_2_VIN) need to be inserted.
    -- =============================================
    -- Stored Procedure for Flatfile_Sales
    -- =============================================
    USE [IconicMarketing]
    ---==========Sales_Cursor
    --USE [IconicMarketing]
    --GO
    DECLARE
    @FileType
    varchar(50),
    @ACDealerID
    varchar(50),
    @ClientDealerID
    varchar(50),
    @DMSType
    varchar(50),
    @DealNumber
    varchar(50),
    @CustomerNumber
    varchar(50),
    @CustomerName
    varchar(50),
    @CustomerFirstName
    varchar(50),
    @CustomerLastName
    varchar(50),
    @CustomerAddress
    varchar(50),
    @CustomerCity
    varchar(50),
    @CustomerState
    varchar(50),
    @CustomerZip
    varchar(50),
    @CustomerCounty
    varchar(50),
    @CustomerHomePhone
    varchar(50),
    @CustomerWorkPhone
    varchar(50),
    @CustomerCellPhone
    varchar(50),
    @CustomerPagerPhone
    varchar(50),
    @CustomerEmail
    varchar(50),
    @CustomerBirthDate
    varchar(50),
    @MailBlock
    varchar(50),
    @CoBuyerName
    varchar(50),
    @CoBuyerFirstName
    varchar(50),
    @CoBuyerLastName
    varchar(50),
    @CoBuyerAddress
    varchar(50),
    @CoBuyerCity
    varchar(50),
    @CoBuyerState
    varchar(50),
    @CoBuyerZip
    varchar(50),
    @CoBuyerCounty
    varchar(50),
    @CoBuyerHomePhone
    varchar(50),
    @CoBuyerWorkPhone
    varchar(50),
    @CoBuyerBirthDate
    varchar(50),
    @Salesman_1_Number
    varchar(50),
    @Salesman_1_Name
    varchar(50),
    @Salesman_2_Number
    varchar(50),
    @Salesman_2_Name
    varchar(50),
    @ClosingManagerName
    varchar(50),
    @ClosingManagerNumber
    varchar(50),
    @F_AND_I_ManagerNumber
    varchar(50),
    @F_AND_I_ManagerName
    varchar(50),
    @SalesManagerNumber
    varchar(50),
    @SalesManagerName
    varchar(50),
    @EntryDate
    varchar(50),
    @DealBookDate
    varchar(50),
    @VehicleYear
    varchar(50),
    @VehicleMake
    varchar(50),
    @VehicleModel
    varchar(50),
    @VehicleStockNumber
    varchar(50),
    @VehicleVIN
    varchar(50),
    @VehicleExteriorColor
    varchar(50),
    @VehicleInteriorColor
    varchar(50),
    @VehicleMileage
    varchar(50),
    @VehicleType
    varchar(50),
    @InServiceDate
    varchar(50),
    @HoldBackAmount
    varchar(50),
    @DealType
    varchar(50),
    @SaleType
    varchar(50),
    @BankCode
    varchar(50),
    @BankName
    varchar(50),
    @SalesmanCommission
    varchar(50),
    @GrossProfitSale
    varchar(50),
    @FinanceReserve
    varchar(50),
    @CreditLifePremium
    varchar(50),
    @CreditLifeCommision
    varchar(50),
    @TotalInsuranceReserve
    varchar(50),
    @BalloonAmount
    varchar(50),
    @CashPrice
    varchar(50),
    @AmountFinanced
    varchar(50),
    @TotalOfPayments
    varchar(50),
    @MSRP varchar(50),
    @DownPayment
    varchar(50),
    @SecurityDesposit
    varchar(50),
    @Rebate
    varchar(50),
    @Term varchar(50),
    @RetailPayment
    varchar(50),
    @PaymentType
    varchar(50),
    @RetailFirstPayDate
    varchar(50),
    @LeaseFirstPayDate
    varchar(50),
    @DayToFirstPayment
    varchar(50),
    @LeaseAnnualMiles
    varchar(50),
    @MileageRate
    varchar(50),
    @APRRate
    varchar(50),
    @ResidualAmount
    varchar(50),
    @LicenseFee
    varchar(50),
    @RegistrationFee
    varchar(50),
    @TotalTax
    varchar(50),
    @ExtendedWarrantyName
    varchar(50),
    @ExtendedWarrantyTerm
    varchar(50),
    @ExtendedWarrantyLimitMiles
    varchar(50),
    @ExtendedWarrantyDollar
    varchar(50),
    @ExtendedWarrantyProfit
    varchar(50),
    @FrontGross
    varchar(50),
    @BackGross
    varchar(50),
    @TradeIn_1_VIN
    varchar(50),
    @TradeIn_2_VIN
    varchar(50),
    @TradeIn_1_Make
    varchar(50),
    @TradeIn_2_Make
    varchar(50),
    @TradeIn_1_Model
    varchar(50),
    @TradeIn_2_Model
    varchar(50),
    @TradeIn_1_ExteriorColor
    varchar(50),
    @TradeIn_2_ExteriorColor
    varchar(50),
    @TradeIn_1_Year
    varchar(50),
    @TradeIn_2_Year
    varchar(50),
    @TradeIn_1_Mileage
    varchar(50),
    @TradeIn_2_Mileage
    varchar(50),
    @TradeIn_1_Gross
    varchar(50),
    @TradeIn_2_Gross
    varchar(50),
    @TradeIn_1_Payoff
    varchar(50),
    @TradeIn_2_Payoff
    varchar(50),
    @TradeIn_1_ACV
    varchar(50),
    @TradeIn_2_ACV
    varchar(50),
    @Fee_1_Name
    varchar(50),
    @Fee_1_Fee
    varchar(50),
    @Fee_1_Commission
    varchar(50),
    @Fee_2_Name
    varchar(50),
    @Fee_2_Fee
    varchar(50),
    @Fee_2_Commission
    varchar(50),
    @Fee_3_Name
    varchar(50),
    @Fee_3_Fee
    varchar(50),
    @Fee_3_Commission
    varchar(50),
    @Fee_4_Name
    varchar(50),
    @Fee_4_Fee
    varchar(50),
    @Fee_4_Commission
    varchar(50),
    @Fee_5_Name
    varchar(50),
    @Fee_5_Fee
    varchar(50),
    @Fee_5_Commission
    varchar(50),
    @Fee_6_Name
    varchar(50),
    @Fee_6_Fee
    varchar(50),
    @Fee_6_Commission
    varchar(50),
    @Fee_7_Name
    varchar(50),
    @Fee_7_Fee
    varchar(50),
    @Fee_7_Commission
    varchar(50),
    @Fee_8_Name
    varchar(50),
    @Fee_8_Fee
    varchar(50),
    @Fee_8_Commission
    varchar(50),
    @Fee_9_Name
    varchar(50),
    @Fee_9_Fee
    varchar(50),
    @Fee_9_Commission
    varchar(50),
    @Fee_10_Name
    varchar(50),
    @Fee_10_Fee
    varchar(50),
    @Fee_10_Commission
    varchar(50),
    @ContractDate
    varchar(50),
    @InsuranceName
    varchar(50),
    @InsuranceAgentName
    varchar(50),
    @InsuranceAddress
    varchar(50),
    @InsuranceCity
    varchar(50),
    @InsuranceState
    varchar(50),
    @InsuranceZip
    varchar(50),
    @InsurancePhone
    varchar(50),
    @InsurancePolicyNumber
    varchar(50),
    @InsuranceEffectiveDate
    varchar(50),
    @InsuranceExpirationDate
    varchar(50),
    @InsuranceCompensationDeduction
    varchar(50),
    @TradeIn_1_InteriorColor
    varchar(50),
    @TradeIn_2_InteriorColor
    varchar(50),
    @PhoneBlock
    varchar(50),
    @LicensePlateNumber
    varchar(50),
    @Cost varchar(50),
    @InvoiceAmount
    varchar(50),
    @FinanceCharge
    varchar(50),
    @TotalPickupPayment
    varchar(50),
    @TotalAccessories
    varchar(50),
    @TotalDriveOffAmount
    varchar(50),
    @EmailBlock
    varchar(50),
    @ModelDescriptionOfCarSold
    varchar(50),
    @VehicleClassification
    varchar(50),
    @ModelNumberOfCarSold
    varchar(50),
    @GAPPremium
    varchar(50),
    @LastInstallmentDate
    varchar(50),
    @CashDeposit
    varchar(50),
    @AHPremium
    varchar(50),
    @LeaseRate
    varchar(50),
    @DealerSelect
    varchar(50),
    @LeasePayment
    varchar(50),
    @LeaseNetCapCost
    varchar(50),
    @LeaseTotalCapReduction
    varchar(50),
    @DealStatus
    varchar(50),
    @CustomerSuffix
    varchar(50),
    @CustomerSalutation
    varchar(50),
    @CustomerAddress2
    varchar(50),
    @CustomerMiddleName
    varchar(50),
    @GlobalOptOut
    varchar(50),
    @LeaseTerm
    varchar(50),
    @ExtendedWarrantyFlag
    varchar(50),
    @Salesman_3_Number
    varchar(50),
    @Salesman_3_Name
    varchar(50),
    @Salesman_4_Number
    varchar(50),
    @Salesman_4_Name
    varchar(50),
    @Salesman_5_Number
    varchar(50),
    @Salesman_5_Name
    varchar(50),
    @Salesman_6_Number
    varchar(50),
    @Salesman_6_Name
    varchar(50),
    @APRRate2
    varchar(50),
    @APRRate3
    varchar(50),
    @APRRate4
    varchar(50),
    @Term2
    varchar(50),
    @SecurityDeposit2
    varchar(50),
    @DownPayment2
    varchar(50),
    @TotalOfPayments2
    varchar(50),
    @BasePayment
    varchar(50),
    @JournalSaleAmount
    varchar(50),
    @IndividualBusinessFlag
    varchar(50),
    @InventoryDate
    varchar(50),
    @StatusDate
    varchar(50),
    @ListPrice
    varchar(50),
    @NetTradeAmount
    varchar(50),
    @TrimLevel
    varchar(50),
    @SubTrimLevel
    varchar(50),
    @BodyDescription
    varchar(50),
    @BodyDoorCount
    varchar(50),
    @TransmissionDesc
    varchar(50),
    @EngineDesc
    varchar(50),
    @TypeCode
    varchar(50),
    @SLCT2
    varchar(50),
    @DealDateOffset
    varchar(50),
    @AccountingDate
    varchar(50),
    @CoBuyerCustNum
    varchar(50),
    @CoBuyerCell
    varchar(50),
    @CoBuyerEmail
    varchar(50),
    @CoBuyerSalutation
    varchar(50),
    @CoBuyerPhoneBlock
    varchar(50),
    @CoBuyerMailBlock
    varchar(50),
    @CoBuyerEmailBlock
    varchar(50),
    @RealBookDate
    varchar(50),
    @CoBuyerMiddleName
    varchar(50),
    @CoBuyerCountry
    varchar(50),
    @CoBuyerAddress2
    varchar(50),
    @CoBuyerOptOut
    varchar(50),
    @CoBuyerOccupation
    varchar(50),
    @CoBuyerEmployer
    varchar(50),
    @Country
    varchar(50),
    @Occupation
    varchar(50),
    @Employer
    varchar(50),
    @Salesman2Commission
    varchar(50),
    @BankAddress
    varchar(50),
    @BankCity
    varchar(50),
    @BankState
    varchar(50),
    @BankZip
    varchar(50),
    @LeaseEstimatedMiles
    varchar(50),
    @AFTReserve
    varchar(50),
    @CreditLifePrem
    varchar(50),
    @CreditLifeRes
    varchar(50),
    @AHRes
    varchar(50),
    @Language
    varchar(50),
    @BuyRate
    varchar(50),
    @DMVAmount
    varchar(50),
    @Weight
    varchar(50),
    @StateDMVTotFee
    varchar(50),
    @ROSNumber
    varchar(50),
    @Incentives
    varchar(50),
    @CASS_STD_LINE1
    varchar(50),
    @CASS_STD_LINE2
    varchar(50),
    @CASS_STD_CITY
    varchar(50),
    @CASS_STD_STATE
    varchar(50),
    @CASS_STD_ZIP
    varchar(50),
    @CASS_STD_ZIP4
    varchar(50),
    @CASS_STD_DPBC
    varchar(50),
    @CASS_STD_CHKDGT
    varchar(50),
    @CASS_STD_CART
    varchar(50),
    @CASS_STD_LOT
    varchar(50),
    @CASS_STD_LOTORD
    varchar(50),
    @CASS_STD_URB
    varchar(50),
    @CASS_STD_FIPS
    varchar(50),
    @CASS_STD_EWS
    varchar(50),
    @CASS_STD_LACS
    varchar(50),
    @CASS_STD_ZIPMOV
    varchar(50),
    @CASS_STD_Z4LOM
    varchar(50),
    @CASS_STD_NDIAPT
    varchar(50),
    @CASS_STD_NDIRR
    varchar(50),
    @CASS_STD_LACSRT
    varchar(50),
    @CASS_STD_ERROR_CD
    varchar(50),
    @NCOA_AC_ID
    varchar(50),
    @NCOA_COA_ADDSRC
    varchar(50),
    @NCOA_COA_MATCH
    varchar(50),
    @NCOA_COA_MOVTYP
    varchar(50),
    @NCOA_COA_DATE
    varchar(50),
    @NCOA_COA_DELCD
    varchar(50),
    @NCOA_COA_RTYPE
    varchar(50),
    @NCOA_COA_RTNCD
    varchar(50),
    @NCOA_COA_LINE1
    varchar(50),
    @NCOA_COA_LINE2
    varchar(50),
    @NCOA_COA_CITY
    varchar(50),
    @NCOA_COA_STATE
    varchar(50),
    @NCOA_COA_ZIP
    varchar(50),
    @NCOA_COA_ZIP4
    varchar(50),
    @NCOA_COA_DPBC
    varchar(50),
    @NCOA_COA_CHKDGT
    varchar(50),
    @NCOA_COA_CART
    varchar(50),
    @NCOA_COA_LOT
    varchar(50),
    @NCOA_COA_LOTORD
    varchar(50),
    @NCOA_COA_URB
    varchar(50),
    @NCOA_COA_Z4LOM
    varchar(50),
    @NCOA_COA_ACTION
    varchar(50),
    @NCOA_COA_QNAME
    varchar(50),
    @NCOA_DPV_AA
    varchar(50),
    @NCOA_DPV_A1
    varchar(50),
    @NCOA_DPV_BB
    varchar(50),
    @NCOA_DPV_CC
    varchar(50),
    @NCOA_DPV_M1
    varchar(50),
    @NCOA_DPV_M3
    varchar(50),
    @NCOA_DPV_N1
    varchar(50),
    @NCOA_DPV_P1
    varchar(50),
    @NCOA_DPV_P3
    varchar(50),
    @NCOA_DPV_RR
    varchar(50),
    @NCOA_DPV_R1
    varchar(50),
    @NCOA_DPV_STATUS
    varchar(50),
    @NCOA_DPV_F1
    varchar(50),
    @NCOA_DPV_G1
    varchar(50),
    @NCOA_DPV_U1
    varchar(50),
    @myerror
    varchar(500),
    @SalesID
    int,
    @errornumber int,
                @errorseverity varchar(500),
                @errorstate int,
                @errorprocedure varchar(500),
                @errorline varchar(50),
                @errormessage varchar(1000);
    DECLARE Sales_Cursor CURSOR FOR 
    SELECT * from FLATFILE_SALES;
    OPEN Sales_Cursor;
     :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    WHILE @@FETCH_STATUS = 0
    BEGIN
    PRINT @VehicleVIN    ;
    --===============================================================================
    -- ****************** insert into Sales Table ***********
    BEGIN TRY
        INSERT INTO Sales 
    IconicDealerID,
    DealNumber,
    CustomerNumber,
    DMSType,
    ContractDate
    VALUES (@ClientDealerID,@DealNumber,@CustomerNumber,@DMSType,@ContractDate);
    END TRY
    BEGIN CATCH
         SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
           :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    @errornumber ,
                @errorseverity ,
                @errorstate,
                @errorprocedure,
                @errorline,
                @errormessage);
    END CATCH
    PRINT @errornumber;
    PRINT @errorseverity;
    PRINT @errorprocedure;
    PRINT @errorline;
    PRINT @errormessage;
    PRINT @errorstate;
    set @myerror = @@ERROR;
        -- This PRINT statement prints 'Error = 0' because
        -- @@ERROR is reset in the IF statement above.
        PRINT N'Error = ' + @myerror;
    set @SalesID = scope_identity();
    PRINT @SalesID;
    --================================================================================
    --Insert into SALES_TRADEIN Table
    BEGIN TRY
    INSERT INTO SALES_TRADEIN
    SalesID,
    TradeIn_VIN,
    TradeIn_Make,
    TradeIn_Model,
    TradeIn_ExteriorColor,
    TradeIn_Year,
    TradeIn_Mileage,
    TradeIn_Gross,
    TradeIn_Payoff,
    TradeIn_ACV,
    TradeIn_InteriorColor
    VALUES
    @SalesID,
    case when  @TradeIn_1_VIN is not null then @TradeIn_2_VIN end,
    case when  @TradeIn_1_Make is not null  then @TradeIn_2_Make end,
    case when  @TradeIn_1_Model is not null  then @TradeIn_2_Model end,
    case when  @TradeIn_1_ExteriorColor is not null  then @TradeIn_2_ExteriorColor end,
    case when @TradeIn_1_Year is not null  then @TradeIn_2_Year end,
    case when  @TradeIn_1_Mileage is not null  then @TradeIn_2_Mileage end,
    case when @TradeIn_1_Gross is not null  then @TradeIn_2_Gross end,
    case when @TradeIn_1_Payoff is not null  then @TradeIn_2_Payoff end,
    case when @TradeIn_1_ACV is not null  then @TradeIn_2_ACV end,
    case when  @TradeIn_1_InteriorColor is not null  then @TradeIn_2_InteriorColor end
    END TRY
    BEGIN CATCH
    SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
          :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    END CATCH

    This is what I've understood from your question. You want to replace @TradeIn_2_VIN value if @TradeIn_1_VIN
    is NULL, else the value of @TradeIn_1_VIN.
    If this is the requirement then, your CASE statement is missing ELSE part. You can re-write this as below
    case when  @TradeIn_1_VIN is null then @TradeIn_2_VIN
    ELSE @TradeIn_1_VIN end,
    or simply you can replace the CASE statement with the below
    COALESCE function,
    COALESCE(@TradeIn_1_VIN, @TradeIn_2_VIN),
    Krishnakumar S

  • How to save images to table using stored procedures?

    hi all,
    i created a stored procedure
    create table members ( id number, name varchar2(30), avatar blob );
    create or replace add_ member ( id number, name varchar2, avatar blob )
    is
    begin
    insert into members values ( id, name, avatar);
    commit;
    end;i have 3 items in page..
    1. Hidden -> P1_ID
    2. Text field - > P1_NAME
    3. File Browse - P1_AVATAR
    but when invoking the procedure in Processes like
    begin
    add_member ( id => :P1_ID, name => :P1_NAME, avatar => :P1_AVATAR );
    end;i get an error
    1 error has occurred
        * ORA-06550: line 3, column 3: PLS-00306: wrong number or types of arguments in call to 'ADD_MEMBERR' ORA-06550: line 3, column 3: PL/SQL: Statement ignoredcan anyone tell me why it errors out?
    thanks
    allen

    Did you do as fac586 suggested:
    create table members ( id number, name varchar2(30), avatar blob );
    create or replace add_ member ( id number, name varchar2, avatar blob )
    is
    begin
    insert into members values ( id, name, avatar);
    commit;
    end;should be something like:
    create table members ( id number, name varchar2(30), avatar blob );
    create or replace add_ member ( id number, name varchar2, avatar blob )
    is
    begin
    insert into members (id, name, avatar) values ( id, name, avatar);
    commit;
    end;You need to specify the columns of the table that you will be inserting values into.
    Also, you should probably rename the parameters of your procedure so you can differentiate between the parameters, and the database columns.
    i.e.:
    create or replace add_ member ( p_id number, p_name varchar2, p_avatar blob )

  • Adding named constraints from another schema using stored procedures

    I need some help. I am trying to create a constraint like Primary key on a table in schema say 'a' from schema 'b'. in Oracle 10g. Schema b has all permissions of create, alter table, create index and other permissions required.
    I can create this constraint from schema b using SQL command 'alter table add constraint...' but not from inside a procedure. I am using 'Execute Immediate' statement to alter table to add constraint. While trying from a procdure, it throws the error as 'insufficeint previleges'.
    Kindly advise.

    it is due to roles.
    if schema b has for example role DBA it is not sufficient. You should
    GRANT ALTER ANY TABLE TO B;maybe also CREATE ANY INDEX. not sure...
    regards
    Laurent

  • How to update all the rows of table using stored procedures

    Hi,
    I want to update all the rows of a table of a specific column
    sp_a  male
    sp_b female
    sp_c  male
    sp_d female
    in above table 
    gender of all the columns has to be interchanged.

    Sir table is like this detail(name varchar(10),gender varchar(10))
    Where Details  are like this 
    Name  Gender
    sp_a 
    male
    sp_b
    female
    sp_c 
    male
    sp_d
    female
    I want to create a stored procedure which automtically updates gender from male to female and female to male
    for all the rows . i.e., all the rows are updated for column gender by just running a stored procedure.
    So after execution of stored proc the above table looks
    Name  Gender
    sp_a 
    female
    sp_b
    male
    sp_c 
    female
    sp_d
    male

  • Form on table: Using stored procedure to update?

    I have a view which joins a handful of tables. I have a PL/SQL API that contains all the necessary business logic and translations to update the tables underlying this view.
    If I use the HTMLDB wizard to create a form on this view, it would automatically generate plain INSERT/UPDATE statements for DML against the view. How can I make it use my API instead? (Yes, I can probably plug in my API in INSTEAD OF triggers on the view, but I really dont want to do that)
    [Of course, the reason I would use the built-in form-on-table wizard is to get the automatic lost-update detection, locking, etc features]
    Help? Thanks

    The wizards are there to help you build typical pages like "form based on a table", "form on based a stored procedure".
    There is no wizard for "form based on a view, using my own API for inserts, updates and delete" - but that doesn't prevent you building such a form by hand. I have built similar forms, and found it quite easy to approach it like this:
    1) use "form based on a stored procedure" to create a form based on your API insert procedure
    2) add further buttons and processes to call your API's update and delete procedures
    3) add an "on load" process to select the row from the view and populate the form for update or delete
    You need to add some logic for context-sensitivity - e.g. Update and Delete buttons only appear when in "update mode", etc.

  • Retreving Hexadecimal Values from a table using SQL query.

    Hi,
    I'm looking for a query to retreive Hexadecimal values contained in a column using SQL query.
    The column contains the values of all types, alphanumeric, numeric and hexadecimal.
    I need to retreive only hexadecimal values.
    any help to me in this regard will be appreciated.
    Thanks

    Presumably, you can be sure that any valid hex value is indeed MEANT to BE a hex value. For example the value 'ACE' is meant to be a hexadecimal value and not the word.

  • Returning array of values from a PL/SQL stored procedure

    I try to run the following example, always happen errors: Run-time error'91' Object variable or With block variable not set.(in line: Set myRS.Source = myCmd1 and Set myRS.Source = myCmd2) Who can tell me where is wrong? I check variable, all set.
    Option Explicit
    Dim myCnn As ADODB.Connection
    Dim myCmd1 As ADODB.Command
    Dim myCmd2 As ADODB.Command
    Dim myRS As ADODB.Recordset
    Dim myConnStr As String
    Dim mySQL As String
    Dim inputssn As Long
    Private Sub cmdGetEveryone_Click()
      Dim myLine As String
      Set myRS.Source = myCmd1
      myRS.Open
      myLine = ""
      While Not myRS.EOF
          myLine = myLine & myRS.AbsolutePosition & " " & _
                   myRS(0) & ", " & myRS(1) & ", " & myRS(2) & vbCrLf
          myRS.MoveNext
      Wend
      MsgBox myLine
      myRS.Close
    End Sub
    Private Sub cmdGetOne_Click()
      Set myRS.Source = myCmd2
      inputssn = InputBox("Enter the SSN you wish to retrieve:")
      myCmd2(0) = inputssn
      myRS.Open
      If myRS.RecordCount = 0 Then
         MsgBox "No data found"
      Else
         MsgBox "Person data: " & myRS(0) & ", " & myRS(1) & ", " & myRS(2)
      End If
      myRS.Close
    End Sub
    Private Sub Form_Load()
      'Using an "On-the-fly" nameless ODBC connection
      'Replace <User ID>, <Password>, and <Server> with the
      'appropriate parameters.
      '  myConnStr = "UID=*****;PWD=*****;driver=" _
      '         & "{Microsoft ODBC for Oracle};SERVER=dseOracle;"
      ' myConnStr = "UID=CSUPerson;pwd=euclid;driver={Microsoft ODBC for Oracle};SERVER=company;"
      'you may also use a named connection DSN such as "myOracleODBC" as follows
      myConnStr = "user id=csuperson;password=euclid;DSN=myOracleODBC;"
      Set myCnn = New ADODB.Connection
      With myCnn
          .ConnectionString = myConnStr
          .CursorLocation = adUseClient
          .Open
      End With
      'the entry RESULTSET 99 indicates the arguments (ssn, fname, lname)
      'are arrays of up to 99 cells each.
      'The binding vars (ssn, fname, lname) should be retrieved in VB using a recordSet
      mySQL = "{call packperson.allperson({RESULTSET 99, ssn, fname, lname})}"
      Set myCmd1 = New ADODB.Command
      With myCmd1
          Set .ActiveConnection = myCnn
          .CommandText = mySQL
          .CommandType = adCmdText
      End With
      mySQL = "{call packperson.oneperson(?,{RESULTSET 2, ssn, fname, " _
             & "lname})}"
      Set myCmd2 = New ADODB.Command
      With myCmd2
          Set .ActiveConnection = myCnn
          .CommandText = mySQL
          .CommandType = adCmdText
          .Parameters.Append .CreateParameter(, adInteger, adParamInput)
      End With
      Set myRS = New ADODB.Recordset
      With myRS
          .CursorType = adOpenStatic
          .LockType = adLockReadOnly
      End With
    End Sub
    Private Sub Form_Unload(Cancel As Integer)
      myCnn.Close
      Set myCnn = Nothing
      Set myCmd1 = Nothing
      Set myCmd2 = Nothing
      Set myRS = Nothing
    End Sub
    Package:
    PACKAGE packperson AS
    TYPE tssn is TABLE of NUMBER(10)
    INDEX BY BINARY_INTEGER;
    TYPE tfname is TABLE of VARCHAR2(15)
    INDEX BY BINARY_INTEGER;
    TYPE tlname is TABLE of VARCHAR2(20)
    INDEX BY BINARY_INTEGER;
    PROCEDURE allperson
    (ssn OUT tssn,
    fname OUT tfname,
    lname OUT tlname);
    PROCEDURE oneperson
    (onessn IN NUMBER,
    ssn OUT tssn,
    fname OUT tfname,
    lname OUT tlname);
    END packperson;
    BODY:
    PACKAGE BODY packperson
    AS
    PROCEDURE allperson
    (ssn OUT tssn,
    fname OUT tfname,
    lname OUT tlname)
    IS
    CURSOR person_cur IS
    SELECT ssn, fname, lname
    FROM employee;
    percount NUMBER DEFAULT 1;
    BEGIN
    FOR singleperson IN person_cur
    LOOP
    ssn(percount) := singleperson.ssn;
    fname(percount) := singleperson.fname;
    lname(percount) := singleperson.lname;
    percount := percount + 1;
    END LOOP;
    END;
    PROCEDURE oneperson
    (onessn IN NUMBER,
    ssn OUT tssn,
    fname OUT tfname,
    lname OUT tlname)
    IS
    CURSOR person_cur IS
    SELECT ssn, fname, lname
    FROM employee
    WHERE ssn = onessn;
    percount NUMBER DEFAULT 1;
    BEGIN
    FOR singleperson IN person_cur
    LOOP
    ssn(percount) := singleperson.ssn;
    fname(percount) := singleperson.fname;
    lname(percount) := singleperson.lname;
    percount := percount + 1;
    END LOOP;
    END;
    END;DB table:
    CREATE TABLE EMPLOYEE
    (FNAME VARCHAR2(15) NOT NULL,
    MINIT    CHAR,
    LNAME VARCHAR2(15) NOT NULL,
    SSN VARCHAR2(9) NOT NULL,
    BDATE DATE,
    ADDRESS VARCHAR2(30),
    SEX CHAR,
    SALARY NUMBER(10,2),
    SUPERSSN VARCHAR2(9),
    DNO NUMBER NOT NULL,
    PRIMARY KEY(SSN));
    DESC EMPLOYEE;
    INSERT INTO EMPLOYEE VALUES
    ('John','B', 'Smith', '123456789','09-JAN-65',
      '731 fONDREN, hOUSTON, TX', 'M', 30000, '333445555',5);
    INSERT INTO EMPLOYEE VALUES
    ('Frankin','T', 'Wong', '333445555','08-DEC-55',
      '683 Voss, Houston,Tx', 'M', 40000, '888665555',5);
    INSERT INTO EMPLOYEE VALUES
    ('Alicia','J', 'Zelaya', '999887777','19-JUL-68',
      '3321Castle, Spring, TX', 'F',25000 , '987654321',4);
    INSERT INTO EMPLOYEE VALUES
    ('Jennifer','S', 'Wallace', '987654321','20-JUN-41',
      '291 Berry, Bellaire, TX', 'F',43000 , '888665555',4);
    INSERT INTO EMPLOYEE VALUES
    ('Ramesh','K', 'Narayan', '666884444','15-SEP-62',
      '975 Fire Oak, Humble, TX', 'F',38000 , '333445555',5);
    INSERT INTO EMPLOYEE VALUES
    ('Joyce','A', 'English', '453453453','31-JUL-72',
      '5631 Rice,Houston,TX', 'F',25000 , '333445555',5);
    INSERT INTO EMPLOYEE VALUES
    ('Ahmad','V', 'Jabbar', '987987987','29-MAR-69',
      '980 Dallas,Houston, TX', 'M',25000 , '987654321',4);
    INSERT INTO EMPLOYEE VALUES
    ('James','E', 'Borg', '888665555','10-NOV-37',
      '450 Stone, Houston, TX', 'M',55000 , null,1);All help I will appreciat it.

    I can't comment on the problem returning PL/SQL arrays, but I will suggest that a more appropriate method of achieving your goal is to call a procedure which returns a REF CURSOR.
    See the examples here:
    http://asktom.oracle.com/~tkyte/ResultSets/index.html

  • Master Data Service: how to remove the dirty data from master data service from a table using store procedure?

    hello, we need to remove the dirty data from MDS, but we found we can only do this from MDS web, and we need to do this by store procedure to make this process automatically. is there any easy method to remove the data from MDS automatically? thank.
    Warren

    Hi Warren,
    Assuming the dirty data is easily identifiable, all you need to do is use the staging process with import type of 5 (de-activate - i.e., soft delete) or import type of 6 (hard delete).
    Could give more details if I knew the version of MDS you are running (SQL 2008R2 or SQL 2012).
    Kind regards,
    M

  • When inserting 3 column details in a single table using Stored Procedure.Only 1 Column details getting inserted.Other 2 Column details are not getting into the table.Please see the below script and help me to change.

    From the Parent Table i need to insert rows which are all under this column {(TradeIn_1_VIN),(TradeIn_2_VIN),(TradeIn_3_VIN) } into SALES_TRADEIN Table .
    I have used the below Query,
    But it reads only (TradeIn _1_Vin) Column in the SALES_TRADEIN table rest 2 records got skipped..
    INSERT INTO SALES_TRADEIN
    SalesID,
    TradeIn_VIN,
    TradeIn_Make,
    TradeIn_Model,
    TradeIn_ExteriorColor,
    TradeIn_Year,
    TradeIn_Mileage,
    TradeIn_Gross,
    TradeIn_Payoff,
    TradeIn_ACV,
    TradeIn_InteriorColor
    VALUES
    @SalesID,
    case when @TradeIn_1_VIN is null then @TradeIn_2_VIN else @TradeIn_1_VIN end,
    case when @TradeIn_1_Make is null then @TradeIn_2_Make else @TradeIn_1_Make end,
    case when @TradeIn_1_Model is null then @TradeIn_2_Model else @TradeIn_1_Model end,
    case when @TradeIn_1_ExteriorColor is null then @TradeIn_2_ExteriorColor else @TradeIn_1_ExteriorColor end,
    case when @TradeIn_1_Year is null then @TradeIn_2_Year else @TradeIn_1_Year end,
    case when @TradeIn_1_Mileage is null then @TradeIn_2_Mileage else @TradeIn_1_Mileage end,
    case when @TradeIn_1_Gross is null then @TradeIn_2_Gross else @TradeIn_1_Gross end,
    case when @TradeIn_1_Payoff is null then @TradeIn_2_Payoff else @TradeIn_1_Payoff end,
    case when @TradeIn_1_ACV is null then @TradeIn_2_ACV else @TradeIn_1_ACV end,
    case when @TradeIn_1_InteriorColor is null then @TradeIn_2_InteriorColor else @TradeIn_1_InteriorColor end
    END TRY
    Actually my problem is
     If  [(TradeIn_1_VIN),(TradeIn_2_VIN),(TradeIn_3_VIN)] these 3 columns have details i need all the 3 columns  details need to be read to SALES_TRADEIN table.
    Suppose if we have data only in [(TradeIn_1_VIN),(TradeIn_2_VIN)] then these column details need to loaded in the SALES_TRADEIN table.
    If any columns are blank no problem it can move next process.
    Please help me change those particular lines to insert all the 3 records  (TradeIn_1_VIN) (TradeIn_2_VIN) (TradeIn_3_VIN) in to the table.

    From SQL2008 on, besides INSERT-SELECT, and INSERT-EXEC, the INSERT-VALUES form of the insert command is improved. It can insert multiple rows like this:
    INSERT INTO my_table(MyColA, MyColB)
    VALUES
    (1, 1),
    (2, 2),
      (3, 3)
    You could also use that in SELECTs, like this:
    SELECT *
    FROM
    (    VALUES (1,2), (3,4)
    ) t(a, b)

  • How to retrieve 2 values from a table in a LOV

    Hi
    I'm pretty new to APEX. I try to retrieve two values from a table using a LOV. I have a table named DEBIT with then columns SITE, NAME and KEY
    I want to display NAME to the user in a list. When the user select an item from the list, I want to retrieve the data of the SITE and KEY column of this item in order to launch an SQL command based on this two values.
    How to retrieve thes two values whant the user chooses an item from the list ?
    I apologize for my english, being french.
    Regards.
    Christian

    Christian,
    From what I understood about your requirement, you want a 'select list with submit' which displays "NAME" and based on the value selected, you want to get the corresponding values for "SITE" and "KEY" from the table.
    <b>Step 1: Create a select list with submit, say P1_MYSELECT </b><br><br>
    Use something like this in the dynamic list of values for the select list: <br>
    SELECT NAME display_value, NAME return_value
    FROM DEBIT<br><br>
    <b>Step 2: Create a page process of type PL/SQL block. Also create 2 hidden items P1_KEY and P1_SITE. </b><br><br>
    In the PL/sQL, write something like:
    DECLARE
      v_key DEBIT.KEY%TYPE;
      v_site DEBIT.SITE%TYPE;
      CURSOR v_cur_myvals IS
              SELECT KEY, SITE
              FROM DEBIT
              WHERE NAME = :P1_MYSELECT;
    BEGIN
      OPEN v_cur_myvals;
      LOOP
              FETCH v_cur_myvals
              INTO  v_key,v_site;
              EXIT WHEN v_cur_myvals%NOTFOUND;
    :P1_KEY := v_key;   
    :P1_SITE := v_site; 
      END LOOP;
      CLOSE v_cur_myvals;
    END; <br><br>
    Then you can use these values for whatever purpose you need to.
    Hope this helps.

  • How to get edited row values from ADF table?

    JDev 11.
    I have a table which is populated with data from Bean.
    I need to save changes after user make changes in any table cell. InputText is defined for table column component.
    I have defined ValueChangeListener for inputText field and AutoSubmit=true. So when user change value in inputText field, method is called:
    public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
    getSelectedRow();
    SaveMaterial(material);
    This method should call getSelectedRow which take values from selected table row and save them into object:
    private Row getSelectedRow(){
    RichTable table = this.getMaterialTable();
    Iterator selection = table.getSelectedRowKeys().iterator();
    while (selection.hasNext())
    Object key = selection.next();
    table.setRowKey(key);
    Object o = table.getRowData();
    material = (MATERIAL) o;
    System.out.println("Selected Material Desc = "+material.getEnumb());
    return null;
    Problem is that getSelectedRow method doesnt get new (edited) values, old values are still used.
    I have tried to use ActiveButton with same method and it works fine in that case. New values are selected from active row and inserted into object.
    JSF:
    <af:table var="row" rowSelection="single" columnSelection="single"
    value="#{ManageWO.material}" binding="#{ManageWO.materialTable}">
    <af:column sortable="false" headerText="E-number">
    <af:inputText value="#{row.enumb}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
    </af:column>
    <af:column sortable="false" headerText="Description">
    <af:inputText value="#{row.desc}" valueChangeListener="#{ManageWO.SaveMaterial}" autoSubmit="true"/>
    </af:column>
    </af:table>
    <af:activeCommandToolbarButton text="Save" action="#{ManageWO.EditData}"/>
    What is a correct place from where save method should be called to get new (edited) values from ADF table?
    Thanks.

    Did you look into the valueChangeEvent?
    It has oldValue and newValue attributes.
    public void SaveMaterial(ValueChangeEvent valueChangeEvent) {
    Object oldVal = valueChangeEvent.getOldValue();
    Object newVal = valueChangeEvent.getNewValue();
    // check if you see what you are looking for.....
    getSelectedRow();
    SaveMaterial(material);
    }Timo

  • Inserting sequence value from JDBC and getting the same value back

    Hi: Gurus I have a table whose primary key is a sequence. I wonder how to make sure I get the same sequence value back for current transaction so I update the other table whose foreign key is the sequence value from first table.
    E.g lets say I do this
    String query_insert = INSERT INTO table1 (column1, ....) VALUES (HIGHLIGHT_ID_SEQ.nextval, ...);
    pstmt = con.prepareStatement(query_insert);
    pstmt.executeUpdate();
    How I make sure no other transaction update the sequence value so I can read the last inserted sequence value and update the second table with this value
    String query_select = "SELECT HIGHLIGHT_ID_SEQ.currval FROM DUAL";
    pstmt = con.prepareStatement(query_select);
    Regards,
    Rashid.

    <rant>No version again. I wonder why people requiring help want to stay anonymous and never want to type their version, only 4 digits. In this case, jdbc, not only the version of the driver is important, but also it's type. Waving a magic wand again? </rant>
    Look up the returning into clause of the insert statement in the sql reference manual for your version.
    Sybrand Bakker
    Senior Oracle DBA

Maybe you are looking for

  • Default Payment Terms on BP2BP B1i Scenario

    Hello Expert, I have designed Business partner to Business Partner scenario from One source to multiple company which is working fine on Live environment, Few BP entries are not posted due to following reason. Source company Payment terms are not pre

  • Inspection Lot not coming in QA16

    Dear Masters, I am using inspection lot origin 04.Inspection is carried out by uaing a task list.As soon as the production confirmation is done , inspection lot is cretaed and  it is seen in QA32.But the same lot is not coming in QA16 , Why?Please su

  • Oracle SFTP adapter Configuration for BPEL  process (11.1.1.3 )

    Hi All, Can someone tell me how to configure the FTP adapter for window's server. We already have a bpel process with FTP adapter but it is set up for unix server , we want to change the location to window's server. Can any one provide me with what c

  • Is possible to revert to older bios version?

    Hello i have a z68a gd65 with a last beta bios because i bought a gtx 770 but i have some problem with it, for example i cant select the ECO mode for more silent system and cant select the OCGENIE mode for more system optimization but only the standa

  • CS5 Interactive pdf problems

    When I export my book to an interactive pdf, the bookmarks generated by the TOC do not work, nor do the Index links or the cross-references. If I create a bookmark from the bookmark panel it seems to work. I heard there was a problem with this - has