Stored procedure as a column in a table
Is it possible to have a column defined as a stored procedure in a table?
I was told that this could be done and that other columns on that row could be used in the stored procedure and you would query the data just as you would for any other column (i.e. select storProcColumn from table).
The reason I am asking is that the column that I want as a stored procedure needs to be calculated every time that column is asked for as it is a calculation from many pieces of data.
The plan is to make a Java stored procedure that will do the calculation, define a column that points to a Java stored procedure, which will do the calculation using data from the row it is in along with other data from other tables.
I am familiar with Java stored procedures but don't know if it is possible to have a column point to it.
Can someone please point me to some documentation?
Thanks,
Dennis
I don't think that you can do exactly what you are expecting, but close. However, without knowing all of your requirements, I don't know if there might be a better way. You will need to use some form of dynamic SQL and it can get complicated and you will need to use functions rather than procedures if you expect to use them in a select statement. I have provided a demonstration below, in which I have created a table with the names of stored functions in one column and the values of parameters to be passed to the functions in the other column. After creating a bunch of java (using examples from the documentation) and some pl/sql, I have ultimately been able to perform a select from your table as you have requested, using just one function. The resulting data contains row counts of tables from one function, where the table name came from the other column in the row and a character string from another function, where the other column is null. I have used if ... end if to allow for the different parameters. Hopefully all of this will either help show you how to do it or help you decide that this is not the way to go and you need to come up with a simpler design for your system.
scott@ORA92> -- tables and data for testing:
scott@ORA92> CREATE TABLE test_tab
2 (col1 VARCHAR2(10),
3 func_col VARCHAR2(10))
4 /
Table created.
scott@ORA92> INSERT INTO test_tab (col1, func_col)
2 VALUES ('dept', 'row_count')
3 /
1 row created.
scott@ORA92> INSERT INTO test_tab (col1, func_col)
2 VALUES ('emp', 'row_count')
3 /
1 row created.
scott@ORA92> INSERT INTO test_tab (col1, func_col)
2 VALUES (NULL, 'HelloWorld')
3 /
1 row created.
scott@ORA92> SELECT * FROM test_tab
2 /
COL1 FUNC_COL
dept row_count
emp row_count
HelloWorld
scott@ORA92> SELECT COUNT (*) FROM dept
2 /
COUNT(*)
4
scott@ORA92> SELECT COUNT (*) FROM emp
2 /
COUNT(*)
14
scott@ORA92> --
scott@ORA92> --
scott@ORA92> -- java and functions to perform calculations
scott@ORA92> -- based on other columns in row and other tables:
scott@ORA92> --
scott@ORA92> -- to count rows in a table:
scott@ORA92> create or replace and compile java source named "RowCounter" as
2 import java.sql.*;
3 import java.io.*;
4 import oracle.jdbc.*;
5
6 public class RowCounter {
7 public static int rowCount (String tabName) throws SQLException {
8 Connection conn =
9 DriverManager.getConnection("jdbc:default:connection:");
10 String sql = "SELECT COUNT(*) FROM " + tabName;
11 int rows = 0;
12 try {
13 Statement stmt = conn.createStatement();
14 ResultSet rset = stmt.executeQuery(sql);
15 while (rset.next()) {rows = rset.getInt(1);}
16 rset.close();
17 stmt.close();
18 } catch (SQLException e) {System.err.println(e.getMessage());}
19 return rows;
20 }
21 }
22 /
Java created.
scott@ORA92> CREATE OR REPLACE FUNCTION row_count (tab_name VARCHAR2) RETURN NUMBER
2 AS LANGUAGE JAVA
3 NAME 'RowCounter.rowCount(java.lang.String) return int';
4 /
Function created.
scott@ORA92> --
scott@ORA92> -- to return specific string:
scott@ORA92> create or replace and compile java source named "Hello" as
2 public class Hello
3 {
4 public static String world ()
5 {
6 return "Hello world";
7 }
8 }
9 /
Java created.
scott@ORA92> create or replace function HELLOWORLD return VARCHAR2 as
2 language java name 'Hello.world () return java.lang.String';
3 /
Function created.
scott@ORA92> --
scott@ORA92> --
scott@ORA92> -- function to calculate and return result using column values
scott@ORA92> -- containing function and table names as parameters
scott@ORA92> -- for dynamic execution:
scott@ORA92> CREATE OR REPLACE FUNCTION get_value
2 (p_func IN VARCHAR2,
3 p_col IN VARCHAR2)
4 RETURN VARCHAR2
5 AS
6 v_result VARCHAR2(20);
7 BEGIN
8 IF p_col IS NULL THEN
9 EXECUTE IMMEDIATE
10 'SELECT ' || p_func || '() FROM DUAL'
11 INTO v_result;
12 ELSE
13 EXECUTE IMMEDIATE
14 'SELECT ' || p_func || '(''' || p_col || ''') FROM DUAL'
15 INTO v_result;
16 END IF;
17 RETURN v_result;
18 END get_value;
19 /
Function created.
scott@ORA92> SHOW ERRORS
No errors.
scott@ORA92> --
scott@ORA92> --
scott@ORA92> -- select statement that selects rows from your table
scott@ORA92> -- and uses the get_value function to pass the column values
scott@ORA92> -- for dynamic execution and return the results:
scott@ORA92> COLUMN result FORMAT A20
scott@ORA92> SELECT col1, func_col, get_value (func_col, col1) AS result
2 FROM test_tab
3 /
COL1 FUNC_COL RESULT
dept row_count 4
emp row_count 14
HelloWorld Hello world
scott@ORA92>
Similar Messages
-
T-sql 2008 r2 place results from calling a stored procedure with parameters into a temp table
I would like to know if the following sql can be used to obtain specific columns from calling a stored procedure with parameters:
/* Create TempTable */
CREATE TABLE #tempTable
(MyDate SMALLDATETIME,
IntValue INT)
GO
/* Run SP and Insert Value in TempTable */
INSERT INTO #tempTable
(MyDate,
IntValue)
EXEC TestSP @parm1, @parm2
If the above does not work or there is a better way to accomplish this goal, please let me know how to change the sql?declare @result varchar(100), @dSQL nvarchar(MAX)
set @dSQL = 'exec @res = TestSP '''+@parm1+''','' '''+@parm2+' '' '
print @dSQL
EXECUTE sp_executesql @dSQL, N'@res varchar(100) OUTPUT', @res = @result OUTPUT
select @result
A complicated way of saying
EXEC @ret = TestSP @parm1, @parm2
SELECT @ret
And not only compliacated, it introduces a window for SQL injection.
Erland Sommarskog, SQL Server MVP, [email protected] -
Stored Procedure to retirive column data
Hello everyone... I am using sql server 2008. I want to retrieve column value if I pass column name as a parameter to my stored procedure without using case statement is there any way to retrieve column values....Please help me..
Hi Sayali,
If the columns LH1 and LC1 are having the correlation like LH2 and LC2,LH3 and LC3 ... LHxx and LCxx, as you'd like to pass only one column LH1, then LC1 can be hard coded in the stored procedure. Please see below.
create table tbl(LH1 varchar(99),LC1 varchar(99));
insert into tbl select 'this is LH1','this is LC1'
go
create proc proc1
@columnName varchar(99)
as
declare @sqlStr nvarchar(max) = N'select @columnName from tbl';
set @sqlStr = replace(@sqlStr,'@columnName',@columnName+','+replace(@columnName,'H','C'));
exec sp_executesql @sqlStr;
go
exec proc1 @columnName='LH1'
drop table tbl;
drop proc proc1
By the way, If this thread is derived from
Stored Procedure with Column Name in Where Clause, the best solution would be the statement in your original post with cases, though it looks not that elegant.
Best regards,
Eric Zhang
TechNet Community Support -
Stored procedure to identify column names from a lookup table
I have a working PL/SQL stored proc as below:
CREATE OR REPLACE PROCEDURE PROC_TEST IS
CURSOR GET_TEST_VALUES IS
SELECT
MF_master.comp_service_b,MF_master.normal_form_amount_b, MF_master.plan_id_b, MF_master.plan_percentage_b, MF_master.plan_service_b,MF_master.autoid, ORA_master.comp_service_v, ORA_master.normal_form_amount_v,
ORA_master.plan_id_v, ORA_master.plan_percentage_v,
ORA_master.plan_service_v, ORA_master.autoid, ORA_master.test_var FROM MF_master, ORA_master
WHERE ((MF_master.autoid = ORA_master.autoid));
BEGIN
FOR REC IN GET_TEST_VALUES LOOP
begin
if rec.test_var='SVC' then
if (to_number(rec.plan_service_b) = to_number(rec.plan_service_v) ) and
(to_number(rec.comp_service_b) = to_number(rec.comp_service_v) ) then
update ORA_master set status_v = 'COMPLETE',last_updt_user_v = 'PROCEDURE',last_updt_date_v = SYSTIMESTAMP where autoid = rec.autoid;
else
update ORA_master set status_v = 'INCOMPLETE',last_updt_user_v = 'PROCEDURE',last_updt_date_v = SYSTIMESTAMP where autoid = rec.autoid;
end if;
end if;
if rec.test_var = 'TERM' then
if (to_number(rec.plan_percentage_b) = to_number(rec.plan_percentage_v) ) and
(to_number(rec.normal_form_amount_b) = to_number(rec.normal_form_amount_v) )
then
update ORA_master set status_v = 'COMPLETE',last_updt_user_v = 'PROCEDURE',last_updt_date_v = SYSTIMESTAMP where autoid = rec.autoid;
else
update ORA_master set status_v = 'INCOMPLETE',last_updt_user_v = 'PROCEDURE',last_updt_date_v = SYSTIMESTAMP where autoid = rec.autoid;
end if;
end if;
end;
END LOOP;
COMMIT;
END;
What I am doing here is, if test_var = 'SVC', I am comparing 2 columns, plan_service_b and comp_service_b(with plan_service_v and
comp_service_v)
Similarly, for test_var = 'TERM', it is plan_percentage_b and normal_form_amount_b(with plan_percentage_v and normal_form_amount_v)
The above works fine as of now, but I am looking for a way to make this design more dynamic. In other words, these comparison columns may change from time
to time and each time something changes, I will have to change this code. Rather, I am looking for a way to have the comparison columns in a
lookup table that I can query to get what needs to be compared.
My thought is :
CREATE TABLE COMPARISON_COL_LOOKUP
(test_var VARCHAR2(10),
MF_column VARCHAR2(30),
ORA_column VARCHAR2(30) );
And then, insert
INSERT INTO COMPARISON_COL_LOOKUP ('SVC','PLAN_SERVICE_B','PLAN_SERVICE_V');
INSERT INTO COMPARISON_COL_LOOKUP ('SVC','COMP_SERVICE_B','COMP_SERVICE_V');
INSERT INTO COMPARISON_COL_LOOKUP ('TERM','PLAN_PERCENTAGE_B','PLAN_PERCENTAGE_V');
INSERT INTO COMPARISON_COL_LOOKUP ('TERM','NORMAL_FORM_AMOUNT_B','NORMAL_FORM_AMOUNT_V');
commit;
In this way, when tomorrow, when something changes - like new columns need to be compared for SVC or TERM, OR, if any comparisons need to
be removed, all I need to do is to change the data in this lookup table !
Now here's my question --- If I have this lookup table, how best can I update my above stored procedure to use this lookup table so that I don't need to
hard-code the column names for comparison ?
Any thoughts/suggestions are appreciated.While it is certainly technically possible to use dynamic SQL here, I would suggest that you make absolutely certain that you're not making things unnecessarily complicated...
Dynamic SQL is generally substantially harder to write, debug, and maintain than equivalent static SQL. In addition, it takes a lot more work to ensure that dynamic SQL performs as well as static SQL (i.e. you now have to explicitly use bind variables) and that you're not introducing security holes via SQL injection.
If your comparisons are likely to change infrequently, and particularly as those changes would imply changes to the underlying requirements, I would tend to be biased toward keeping the working procedure and just planning on making code changes periodically.
Of course, not knowing your particular requirements, I certainly can't be certain that dynamic SQL would be inappropriate here, but I have seen lots of folks unnecessarily complicate their systems by building overly flexible systems that were painful to support and extend.
Justin -
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 CATCHThis 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 -
Calling stored procedure from a column in report
Hi All,
I am new to APEX. I did a search on this forum but couldnt get an exact answer.
I know how to call or execute a stored procedure from a button. like create a PL/SQL anonymous bloack and asssociate it with the button.
my issue is a bit different. I have a report with 11 columns. the last column just says 'delete' for all the rows(i did this in my report query like SELECT x,y,z,...., 'delete' AS delete). when i click this cell for any row(this column can be a hyperlink or any clickable element), i want to call a stored procedure that takes parameters as the values in column 2 and column 4 for that particular row.
for example, my report looks somethnig like below,
FILE_ID MEMBER_CD ACTION
112 ABCD delete
113 WXYYZ delete
114 PQRS delete
i want to click the 'delete' in first row that should call a stored procedure and pass 112 and ABCD as parameters to the procedure.
i have the procedure as a process now. sturggling to bind this column to procedure but no success :(
Hope am clear. Please any help is appreciated.
ThanksThanks man! that was a great help. looks like i am almost there. i created those items t obe hidden.
now i am passing three parameters to the procedure. my url for that column value looks like this,
javascript:P65_PARTITION_ID=#PARTITION_ID#;P65_DBC=#DBC#;P65_FILE_ID=#FILE_ID#;doSubmit('Sku_Save');
the #DBC# parameter is a name of the person that has spaces(firstname lastname). i am getting a javascript error saying,
Line: 1
Char: 37
Error:Expected ';'
i see that char 37 is the space after firstname.
any idea how i should get rid of this error.
Also, as you have been very helpful, a question further beyond :). the above procedure will return a OUT varchar parameter. i guess i have to create another item for that. how do i read it and display just below my report as text.
Thanks Again! -
Stored procedure with database link with "from table(...)"
Hi guys,
I've been told I can't create views on a database by the design team and so have to use this stored procedure to obtain the values.
select HAN_ID, HAN_DS, GLOBAL_IN, LOCAL_IN
from table(cast(ODADMIN.ODP00002_QUERY.Execute001@DBLINK(11312,'EN') as
ODADMIN.ODP00002_001_Array@DBLINK)) WHERE LOCAL_IN = 'Y';I've been told that it works when you remove the database links (so on the actual database) when you remove the cast part. I've tried it with my link and with/without the cast part but it doesn't work. With the example above I get the error: ORA-00907: missing right parenthesis.
When I remove the CAST-AS and the additional parenthesis it brings i get the error: ORA-00904: "ODADMIN"."ODP00002_QUERY"."EXECUTE001": invalid identifier
When I do table( *"* ODADMIN.ODP00002_QUERY.Execute001@MWW_DEV(11312,'EN') *"* )... -- wrapping the call in speech marks I get: ORA-00972: identifier is too long
Anyone see what's wrong? Thanks for any help.
MikeHi Ben,
Asking now. By a view I mean one local to the database; I could create one on APEX but then I use the database link twice instead of just 1.
His reasoning Ben:
Firstly, Maintenance. We will have to maintain additional views (at additional code). Secondly, if the view has a JOIN, then you can't update through it (without complexities). If we have to get the View to pass the data to a Procedure (that's a pain). Also, standards..
All update occur via either a Procedure, or a Base view, across over 1000 tables
That's the standard, and doing things differently is costly long term
People will not know how it works, it will have to be explained, maintained..etc.
If the Application has the Business Rules, then updates via Base Views, that's a more standard way of developing. Also, if you update via this view, you'll update multiple rows in one call, which is in-effficient if only ONE row needs to change. Therefore, single row updates from the Application is more efficient
The procedure is as follows:
--SET SERVEROUTPUT ON
DECLARE
nPBusLoc NUMBER(5):=11312;
sPHanId VARCHAR2(3):='SB1';
sPLngId VARCHAR2(2):='EN';
sPDesc VARCHAR2(30);
sPAllowAlloc VARCHAR2(1);
sPShowEnq VARCHAR2(1);
sPAllowDel VARCHAR2(1);
sPShowScan VARCHAR2(1);
sPGlobalLocal VARCHAR2(1);
sPReturnCd VARCHAR2(2);
sPReturnTx VARCHAR2(100);
BEGIN
ODADMIN.ODP00001.getHandlingCodes
(nPBusLoc -- IN NUMBER
,sPHanId -- IN VARCHAR2
,sPLngId -- IN VARCHAR2
,sPDesc -- OUT VARCHAR2
,sPAllowAlloc -- OUT VARCHAR2
,sPShowEnq -- OUT VARCHAR2
,sPAllowDel -- OUT VARCHAR2
,sPShowScan -- OUT VARCHAR2
,sPGlobalLocal-- OUT VARCHAR2
,sPReturnCd -- OUT VARCHAR2
,sPReturnTx -- OUT VARCHAR2
DBMS_OUTPUT.PUT_LINE('nPBusLoc = '||nPBusLoc );
DBMS_OUTPUT.PUT_LINE('sPHanId = '||sPHanId );
DBMS_OUTPUT.PUT_LINE('sPLngId = '||sPLngId );
DBMS_OUTPUT.PUT_LINE('sPDesc = '||sPDesc );
DBMS_OUTPUT.PUT_LINE('sPAllowAlloc = '||sPAllowAlloc );
DBMS_OUTPUT.PUT_LINE('sPShowEnq = '||sPShowEnq );
DBMS_OUTPUT.PUT_LINE('sPAllowDel = '||sPAllowDel );
DBMS_OUTPUT.PUT_LINE('sPShowScan = '||sPShowScan );
DBMS_OUTPUT.PUT_LINE('sPGlobalLocal = '||sPGlobalLocal );
DBMS_OUTPUT.PUT_LINE('sPReturnCd = '||sPReturnCd );
DBMS_OUTPUT.PUT_LINE('sPReturnTx = '||sPReturnTx );
END;
/Mike
Edited by: Dird on 27-Aug-2009 01:50 -
Creating stored procedure to import csv data into tables
I am trying to create a stored procedure to import data from a csv file into a table. I tried using sqlldr but could not run it at school due to access permissions that they will not change. So I looked at the utl_package and from what I can see it requires a "virtual" directory, which conflicts with the access permissions again at school. So can I create a stored procedure that will just read data from a csv file into a table without the need to write or create a file/directory.
ThankyouSatyaki_De wrote:
Since, you are talking about so much restriction - i don't think you will get that.
One alternative solution can be -> write a java based pl/sql procedure and try load that by parsing it. But, for that you need execute privileges on dbms_java package.
Do you have that? I doubt.
Regards.
Satyaki De.Nope not allowed to use java, and im new to oracle. Why can't a stored procedure in pl/sql just read a file and put the data into a table I create prior? -
Stored Procedure to delete a number of tables with a common name attribute
Hi All,
This is my first post so I hope I have posted to the required level with sufficient information. This is my first stored procedure (SP) and is for Oracle 10.
I am trying to write a script to delete 11 tables and some rows from another 3 tables, all of which are named with a number that I would like to input at the point of creation of the SP. Below is the script I have written and edited. My original has been lost by crashing servers!
When I run the script it gives me the following output:
"Warning: execution complete with warning
procedure ScenarioDelete compiled"
The SP hasn't deleted any of the tables and I'm not sure if it's because my script is poor or because of something else. Any help is greatly appreciated!!
-- table delete SP
-- Run begin ScenarioDelete ('x'); with x as the ScenarioId
create or replace procedure ScenarioDelete (ScenarioNo IN varchar2);
countstable := 'C_' || ScenarioNo;
changetable := 'CG_' || ScenarioNo;
countsinfotable := 'CI_' || ScenarioNo;
datatable1 := 'D_0_' || ScenarioNo;
datatable2 := 'D_1_' || ScenarioNo;
datatable3 := 'D_2_' || ScenarioNo;
hietable1 := 'HI_0_' || ScenarioNo;
hietable2 := 'HI_1_' || ScenarioNo;
hietable3 := 'HI_2_' || ScenarioNo;
hielinktable1 := 'HL_1_' || ScenarioNo;
hielinktable2 := 'HL_2_' || ScenarioNo;
AS
execute immediate 'drop table ' || countstable;
execute immediate 'drop table ' || changetable;
execute immediate 'drop table ' || countsinfotable;
execute immediate 'drop table ' || datatable1;
execute immediate 'drop table ' || datatable2;
execute immediate 'drop table ' || datatable3;
execute immediate 'drop table ' || hietable1;
execute immediate 'drop table ' || hietable2;
execute immediate 'drop table ' || hietable3;
execute immediate 'drop table ' || hielinktable1;
execute immediate 'drop table ' || hielinktable2;
execute immediate 'delete from USERACESS where SCENARIOID = ' || ScenarioNo;
execute immediate 'delete from SCENARIO where SCENARIOID = ' || ScenarioNo;
execute immediate 'delete from SCENARIOINFO where SCENARIOID = ' || ScenarioNo;
-- or --
execute immediate 'delete from USERACESS where SCENARIOID = '' || ScenarioNo || ''';
execute immediate 'delete from SCENARIO where SCENARIOID = '' || ScenarioNo || ''';
execute immediate 'delete from SCENARIOINFO where SCENARIOID = '' || ScenarioNo || ''';
END;Hi,
Welcome to the forum!
When you compile a stored procedure, you get only the vaguest of error messages by default.
Always say SHOW ERRORS immediately after compiling, to get more detailed error messages. (And, of course, post the complete error message, including line number, when you need help.)
Remember to specify a datatype (and, in the case of VARCHAR2 variables, a maximum length) for all local variables you declare:
create or replace procedure ScenarioDelete (ScenarioNo IN varchar2) -- no semicolon here
AS -- AS or IS (it doesn't matter which) required here
countstable VARCHAR2 (50) := 'C_' || ScenarioNo;
changetable VARCHAR2 (50) := 'CG_' || ScenarioNo;
...You're not actually wasting any space if you decalre the variable as 50 characters, but only use 3.
It really helps if you format code, so that, for example,
all the local variables are indented before the word BEGIN
everything between BEGIN and its corresponding END is indented
everything between IF and its corresponding END IF is indented,
and so on.
You're probably already doing that, but it doesn't show up on this site unless you type these 6 characters
(small letters only, inside curly brackets) before and after the formatted text.
That's what I did for the code fragement above.
Edited by: Frank Kulash on Mar 23, 2009 12:04 PM
Formatting stuff added. -
Block based on Stored Procedure - Update Changed columns only
If I were to base a block on stored procedures that includes an Update procedure but only update SOME of the updateable columns, what happens?
Does the Form send to server ONLY
1) The rows that were updated
2) The columns that updated
3) All columns in the row being updated regardless of whether they were updated
Is the correct answer 1) + 2) or 1) + 3)
Please help.
ThanksHello,
<p>There is another example here</p>
Francois -
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) -
Stored Procedure with in out parameter of table of records type
Hi
I am tring to create a strore procedure inside a package like this:
procedure name_p(root in table.column%type, tab in out table_of_records_type);
I get the error:
PLS-00306: Wrong number or types of arguments in call to 'name_p'
I am working with oracle 8.1.7.
I dont really understand why this is happening.
Can anyone suggest anything.
Thnx
EdAn example :
TEST@db102 SQL> select ename, job from emp
2 where empno = 7902;
ENAME JOB
FORD ANALYST
TEST@db102 SQL> create or replace procedure show_emp (
2 v_empno in number,
3 v_ename out varchar2,
4 v_job out varchar2 )
5 is
6 begin
7 select ename, job into v_ename, v_job
8 from emp
9 where empno = v_empno;
10 end;
TEST@db102 SQL> /
Procedure created.
TEST@db102 SQL> exit
Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
[ora102 work db102]$ IN=7902
[ora102 work db102]$ set `sqlplus -s test/test@db102 << !
var out1 varchar2(30);
var out2 varchar2(30);
set pages 0
set feed off
exec show_emp($IN,:out1,:out2);
print
exit
`[ora102 work db102]$ echo $1 $2
FORD ANALYST
[ora102 work db102]$ -
Stored procedure in package return multiple columns from multiple tables
Hi ,
Can a single stored procedure return multiple column values from different tables.
example:
tabA: col2, tabB:col3,tabC:col4 etc.
one more question:
if a stored procedure like to return 10 columns for a particular record from a single table do i need to define a TYPE statement for each colum like
TYPE col1 is TABLE of varchar
TYPE col2 is TABLE of varchar
here i want to return only one row, not many rows.
thanksYou can try one procedure with OUT or IN/OUT parameters that collect the values from one or more sql statements.
CREATE OR REPLACE PROCEDURE P1
(P_COD IN TABLE.COD%TYPE,
P_DESC1 OUT TABLE1.DESC1%TYPE,
P_DESC2 OUT TABLE2.DESC2%TYPE)
IS
BEGIN
SELECT table1.DESC1, table2.DESC2
INTO P_DESC1, P_DESC2
FROM TABLE1, table2 WHERE
table1.COD = P_COD and
table1.cod = table2.cod ;
END P1;
JP -
Stored procedure Update Statement missing column dynamic creation
Hi All,
Here is my scenario. I am having Stored procedure with 5 parameters for particular table. But table schema is having only 3 columns. Is there any way to create 2 missing columns dynamically while Stored Procedure is running?. How can we handle the missing column
exception. Please help me.
Thanks,Sakthi
Thanks and Regards, SakthiHi All,
Here is my scenario. I am having Stored procedure with 5 parameters for particular table. But table schema is having only 3 columns. Is there any way to create 2 missing columns dynamically while Stored Procedure is running?. How can we handle the missing column
exception. Please help me.
Thanks,Sakthi
Thanks and Regards, Sakthi
Very bizarre requirement - surely you meant Temporary Table.
For physical table, it would be a good idea to check if column already exists then ADD columns as per Uri Dimant's post.
if exists(select * from sys.columns
where Name = N'columnName' and Object_ID = Object_ID(N'tableName'))
begin
-- Column Exists
end
web: www.ronnierahman.com -
Can I create a Stored Procedure That access data from tables of another servers?
I'm developing a procedure and within it I'm trying to access another server and make a select into a table that belongs to this another server. When I compile this procedure I have this error message: " PLS-00904: insufficient privilege to access object BC.CADPAP", where BC.CADPAP is the problematic table.
How can I use more than one connection into an Oracle Stored Procedure?
How I can access tables of a server from a Stored Procedure since the moment I'm already connected with another server?
Can I create a Stored Procedure That access data from tables of another servers?You need to have a Database Link between two servers. Then you could do execute that statement without any problem. Try to create a database link with the help of
CREATE DATABASE LINK command. Refer Document for further details
Maybe you are looking for
-
IMessage not showing contact names
I just recently downloaded and installed OS X Mavericks on my 2011 iMac and trying to get up and running with the new iMessage app. But there are two major bugs I can figure out how to fix if anyone can help me fix these problems or comment if your h
-
Canon MX870 prints incredibly slow via WIFI
I have an MX870 with an iMac quad core running OSX 10.6 and a netgear router. I don't use a USB cable because the run would exceed 15' because of the way the furniture is layed out where the computer and printer are, and the USB cable is too long to
-
How to convert a 16-bit image to 8-bit
I am having difficulties in skeletonizing my image. Although I already threshold my image, it still cannot be skeletonized. When I create the image using IMAQ create, the image type must be set to 16-bit, otherwise it will create an error message. An
-
PHP5 OCI8 Oracle Client on MacOS X Leopard - Installation Script
Hello, There is a new bash scripts for the installation and configuration of Apache2, PHP5, Oracle Client v10.2 and OCI8 on MacOS X running Leopard. The script was tested on Leopard 10.5.4. It should work with the pervious versions of Leopard but I d
-
Developing a web site on the Mac
Hi, Just wanted to get some tips for developing a website on the Mac. 1. iWeb (I have iWeb that came with iLife '06) seems interesting enough. But is there a place where some more professional looking templates can be downloaded or bought? 2. What ar