Exceptions raised by Insert statement
In procedure insert statement raising value_error,invalid_error. so how to capture this errors?
code:
insert into table_name values(....);
exception
when ?
Hi,
You must change NULL statements for appropiate statements. For more information please check [Summary of Predefined PL/SQL Exceptions|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/errors.htm#sthref1966]
BEGIN
INSERT INTO table_name
VALUES
EXCEPTION
WHEN INVALID_NUMBER THEN
NULL;
WHEN DUP_VAL_ON_INDEX THEN
NULL;
WHEN OTHERS THEN
NULL;
END;
/Regards,
Similar Messages
-
Exception handling for all the insert statements in the proc
CREATE PROCEDURE TEST (
@IncrStartDate DATE
,@IncrEndDate DATE
,@SourceRowCount INT OUTPUT
,@TargetRowCount INT OUTPUT
,@ErrorNumber INT OUTPUT
,@ErrorMessage VARCHAR(4000) OUTPUT
,@InsertCase INT --INSERT CASE INPUT
WITH
EXEC AS CALLER AS
BEGIN --Main Begin
SET NOCOUNT ON
BEGIN TRY
DECLARE @SuccessNumber INT = 0
,@SuccessMessage VARCHAR(100) = 'SUCCESS'
,@BenchMarkLoadFlag CHAR(1)
,@BenchmarkFlow INT
,@MonthYearStart DATE
,@MonthYearEnd DATE
,@StartDate DATE
,@EndDate DATE
/* Setting the default values of output parameters to 0.*/
SET @SourceRowCount = 0
SET @TargetRowCount = 0
/*Setting the Start and end date for looping */
SET @MonthYearStart = @IncrStartDate;
SET @MonthYearEnd = @IncrEndDate;
/* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
@InsertCase =0 means data will be inserted in the target TAB1
@InsertCase =1 means data will be inserted in the target TAB2
@InsertCase =2 means data will be inserted in the target TAB3
@InsertCase =3 means data will be inserted in the target TAB4
@InsertCase =4 means data will be inserted in the target TAB5
@InsertCase =5 means data will be inserted in the target TAB6
if @InsertCase =0
WHILE (@MonthYearStart <= @MonthYearEnd)
BEGIN
SET @StartDate = @MonthYearStart;
SET @EndDate = @MonthYearEnd;
/* Delete from target where date range given from input parameter*/
DELETE FROM TAB1
WHERE [MONTH] BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
AND [YEAR] BETWEEN year(@StartDate) and year(@EndDate)
/*Insert data in target-TAB1 */
BEGIN TRANSACTION
INSERT INTO TAB1
A,B,C
SELECT
A,BC
FROM XYZ
COMMIT TRANSACTION
SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
END -- End of whileloop
END TRY
BEGIN CATCH
IF @@TRANCOUNT>0
ROLLBACK TRANSACTION
SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
END CATCH
END--End of Main Begin
I have the above proc inserting data based on parameters where in @InsertCase is used for case wise execution.
I have written the whole proc with exception handling using try catch block.
I have just added one insert statement here for 1 case now I need to add further insert cases
INSERT INTO TAB4
A,B,C
SELECT
A,BC
FROM XYZ
INSERT INTO TAB3
A,B,C
SELECT
A,BC
FROM XYZ
INSERT INTO TAB2
A,B,C
SELECT
A,BC
FROM XYZ
I will be using following to insert further insert statements
if @InsertCase =1
I just needed to know where will be my next insert statement should be fitting int his code so that i cover exception handling for all the code
MudassarHi Erland & Mudassar, I have attempted to recreate Mudassar's original problem..here is my TABLE script;
USE [MSDNTSQL]
GO
/****** Object: Table [dbo].[TAB1] Script Date: 2/5/2014 7:47:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TAB1](
[COL1] [nvarchar](1) NULL,
[COL2] [nvarchar](1) NULL,
[COL3] [nvarchar](1) NULL,
[START_MONTH] [int] NULL,
[END_MONTH] [int] NULL,
[START_YEAR] [int] NULL,
[END_YEAR] [int] NULL
) ON [PRIMARY]
GO
Then here is a CREATE script for the SPROC..;
USE [MSDNTSQL]
GO
/****** Object: StoredProcedure [dbo].[TryCatchTransactions1] Script Date: 2/5/2014 7:51:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TryCatchTransactions1] (
@IncrStartDate DATE
,@IncrEndDate DATE
,@SourceRowCount INT OUTPUT
,@TargetRowCount INT OUTPUT
,@ErrorNumber INT OUTPUT
,@ErrorMessage VARCHAR(4000) OUTPUT
,@InsertCase INT --INSERT CASE INPUT
WITH
EXEC AS CALLER AS
BEGIN --Main Begin
SET NOCOUNT ON
BEGIN TRY
DECLARE @SuccessNumber INT = 0
,@SuccessMessage VARCHAR(100) = 'SUCCESS'
,@BenchMarkLoadFlag CHAR(1)
,@BenchmarkFlow INT
,@MonthYearStart DATE
,@MonthYearEnd DATE
,@StartDate DATE
,@EndDate DATE
/* Setting the default values of output parameters to 0.*/
SET @SourceRowCount = 0
SET @TargetRowCount = 0
/*Setting the Start and end date for looping */
SET @MonthYearStart = @IncrStartDate;
SET @MonthYearEnd = @IncrEndDate;
/* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
@InsertCase =0 means data will be inserted in the target TAB1
@InsertCase =1 means data will be inserted in the target TAB2
@InsertCase =2 means data will be inserted in the target TAB3
@InsertCase =3 means data will be inserted in the target TAB4
@InsertCase =4 means data will be inserted in the target TAB5
@InsertCase =5 means data will be inserted in the target TAB6
IF @InsertCase =0
WHILE (@MonthYearStart <= @MonthYearEnd)
BEGIN
SET @StartDate = @MonthYearStart;
SET @EndDate = @MonthYearEnd;
/* Delete from target where date range given from input parameter*/
DELETE FROM TAB1
WHERE START_MONTH BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
AND START_YEAR BETWEEN year(@StartDate) and YEAR(@EndDate)
/*Insert data in target-TAB1 */
BEGIN TRANSACTION
INSERT INTO TAB1 (COL1,COL2,COL3)
VALUES ('Z','X','Y')
SELECT COL1, COL2, COL3
FROM TAB1
COMMIT TRANSACTION
SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
END -- End of whileloop
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION
SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
END CATCH
PRINT @SUCCESSMESSAGE
END--End of Main Begin
GO
I am just trying to help --danny rosales
UML, then code -
Using the Insert statement in a Java program without hardcoding the data
hello.
this is james mcfadden. i have developed a program called Demo.java, which is used with another program called QueryTableModel.java (a program that allows data to be viewed in a JTable). The Demo.java program displays a menu, connects to a database, allows the user to add data into the database and allows the user to view data that is already in the database. I have a problem with the Demo.java program. I have hardcoded the Insert statement in it. How do you use the Insert statement to put data into a database without hardcoding the data?
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
import javax.swing.JOptionPane;//provides a class that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";//a static variable that allows a connection to be made to a database called VideoLibrary
static Statement stmt;//a static variable that allows a statement to be made once a connection is set up
static Connection con;//a static interface that allows a connection to be made to a database
//global variables
JTextField hostField;//a class that allows a line of text to be changed
JTextField queryField;//a class that allows a line of text to be changed
QueryTableModel qtm;//a class that shows and changes regular two-dimensional tables of cells
JComboBox comboBox;//a class that puts a button or editable field and a drop-down list together
public static void main(String args[]){
int choice=-1;//a variable of type int that is set to -1
do{
choice=getChoice();//invokes the method getChoice()
if(choice!=0){
getSelected(choice);//invokes the method getSelected(choice)
}//end if
//if the user chooses 5, it will cause him or her to exit the system
}while(choice!=5);//end do-while
System.exit(0);//closes down the menu screen
}//end main
public static int getChoice(){
String choice;//a variable of type string
int ch;//a variable of type int
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");//asks the user for some input
ch = Integer.parseInt(choice);//a class that wraps a value of the primitive type int in an object
return ch;//a method that returns an integer value
}//end getChoice
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();//invokes the method maintainProductDetails()
}//end if
if(choice==2){
maintainMemberDetails();//invokes the method maintainMemberDetails()
}//end if
if(choice==3){
maintainRentalDetails();//invokes the method maintainRentalDetails()
}//end if
if(choice==4){
Demo test = new Demo();//invokes the constructor Demo()
test.setVisible(true);//shows the JTable component by marking it as visible
}//end if
}//end getSelected
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used to create a JDBC connection using a database
}//end try
catch(java.lang.ClassNotFoundException e){//causes an exception to be thrown when an application tries to load in a class through its string name
System.err.print("ClassNotFoundException: ");//displays an error message
System.err.println(e.getMessage());//returns the exception that was raised if an error occurred while attempting to load the ClassNotFoundException class
}//end catch
try {
con=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
return con;
}//end getConnection
public static void maintainProductDetails(){
Connection con = getConnection();//creates a connection with the database
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;//string variables that represent information about the different types of product data that will be stored in the database
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, 'Pussy Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainProductDetails
public static void maintainMemberDetails(){
Connection con = getConnection();//creates a connection with the database
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;//string variables that represent information about the member data that will be stored in the database
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainMemberDetails
public static void maintainRentalDetails(){
Connection con = getConnection();//creates a connection with the database
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;//string variables that represent information about the loan data that will be stored in the database
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainRentalDetails
public Demo(){//a constructor
super("Demo Test Frame");//overrides the constructor
setSize(350, 200);//Resizes this component so that it has width of 350 and height of 200
comboBox = new JComboBox();//invokes the class JComboBox
comboBox.addItem("jdbc:odbc:VideoLibrary");//adds the specified item to the end of the scrolling list
qtm = new QueryTableModel();//invokes the class QueryTableModel
JTable table = new JTable(qtm);//a class that shows and changes regular two-dimensional tables of cells
JScrollPane scrollpane = new JScrollPane(table);//a class that provides a scrollable view of a lightweight component
JPanel p1 = new JPanel();//a class that puts the combo box and query field in a panel
p1.setLayout(new GridLayout(3, 2));//Sets the layout manager for this container
p1.add(comboBox);//Appends the specified component to the end of this container
p1.add(new JLabel("Enter your query: "));//Appends the specified component to the end of this container
p1.add(queryField = new JTextField());//Appends the specified component to the end of this container
p1.add(new JLabel("Click here to send: "));//Appends the specified component to the end of this container
JButton jb = new JButton("Search");//a class that is an implementation of a "push" button
jb.addActionListener(new ActionListener(){//Adds an ActionListener to the button
public void actionPerformed(ActionEvent e){
qtm.setHostURL();//invokes the method setHostURL
qtm.setQuery(queryField.getText().trim());//invokes the method setQuery; and returns the text that is presented by this text component and returns a copy of the string, with leading and trailing whitespaces omitted
} );//end addActionListener
p1.add(jb);//Appends the specified component to the end of this container
getContentPane().add(p1, BorderLayout.NORTH);//Returns the content pane
getContentPane().add(scrollpane, BorderLayout.CENTER);//Returns the content pane
}//end Demo
}//end class Demo
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.util.Vector;//provides a class that implements a growable array of objects
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
public class QueryTableModel extends AbstractTableModel{
Vector cache;//a class that constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
int colCount;//a variable that counts the number of columns in the three tables
String[] headers;//a class that represents character strings and all string literals in this program are implemented as instances of the String class
Connection db;//an interface that allows a connection to be made to a database
Statement statement;//an interface that allows executes the given SQL statement, which returns a single ResultSet object
String currentURL;//a variable that allows the URL to be displayed in a combo box
public QueryTableModel(){//a constructor
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used by opening a JDBC connection using an URL
}//end try
catch(Exception e){
System.out.println("problem loading the driver ");//an error message
}//end catch
}//end QueryTableModel
public String getColumnName(int i){//Returns the designated column's name
return headers;//returns the name of each column in the three table
}//end getColumnName
public int getColumnCount(){//Returns the number of columns in the column model
return colCount;//returns the number of columns in the three tables
}//end getColumnCount
public int getRowCount(){//Returns the number of rows in this table's model
return cache.size();//returns the number of components in the vector
}//end getRowCount
public Object getValueAt(int row, int col){//Returns the cell value at row and column
return ((String[])cache.elementAt(row))[col];//Returns the component at the specified index
}//end getValueAt
public void setHostURL(){//sets the URL for the database
String url = "jdbc:odbc:VideoLibrary";//a variable that allows a connection to be made to a database called VideoLibrary
closeDB();//invokes the method closeDB()
try{
db=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setHostURL
public void setQuery(String q){//sets the kind of query that is to be sent to the database
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
String s="select * from Product";//a variable that causes all the data that is in the product table to be displayed in a JTable, which also means that all the data that is in both the member and rental tables can also be displayed in a JTable
try{
ResultSet rs=statement.executeQuery(q);//an interface that is used to generate a database result set by executing a statement that queries the database
ResultSetMetaData meta=rs.getMetaData();//an interface that is used to get information about the types and properties of the columns in a ResultSet object
colCount=meta.getColumnCount();//Returns the number of columns in this ResultSet object
headers=new String[colCount];//gets the name of each column in the three tables
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);//Get the designated column's name
}//end for
while(rs.next()){
String[] record=new String[colCount];//stores the name of each column in the three tables in memory
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);//Retrieves the value of the designated column in the current row of this ResultSet object as a String
}//end for
cache.addElement(record);//Adds the specified component to the end of this vector, increasing its size by one
}//end while
fireTableChanged(null);//Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model
}//end try
catch(Exception e){
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setQuery
public void initDB(String url){
try{
db=DriverManager.getConnection(url);//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end initDB
public void closeDB(){
try{
if(statement!=null){
statement.close();//Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed
}//end if
if(db!=null){
db.close();//Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released
}//end if
}//end try
catch(Exception e){
System.out.println("Could not close the current connection.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end closeDB
}//end class QueryTableModelhere's an uncommented version of the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JOptionPane;
import java.sql.*;
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";
static Statement stmt;
static Connection con;
JTextField hostField;
JTextField queryField;
QueryTableModel qtm;
JComboBox comboBox;
public static void main(String args[]){
int choice=-1;
do{
choice=getChoice();
if(choice!=0){
getSelected(choice);
}while(choice!=5);
System.exit(0);
public static int getChoice(){
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");
ch = Integer.parseInt(choice);
return ch;
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();
if(choice==2){
maintainMemberDetails();
if(choice==3){
maintainRentalDetails();
if(choice==4){
Demo test = new Demo();
test.setVisible(true);
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(java.lang.ClassNotFoundException e){
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
try {
con=DriverManager.getConnection(url,"","");
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
return con;
public static void maintainProductDetails(){
Connection con = getConnection();
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, '***** Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainMemberDetails(){
Connection con = getConnection();
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainRentalDetails(){
Connection con = getConnection();
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public Demo(){
super("Demo Test Frame");
setSize(350, 200);
comboBox = new JComboBox();
comboBox.addItem("jdbc:odbc:VideoLibrary");
qtm = new QueryTableModel();
JTable table = new JTable(qtm);
JScrollPane scrollpane = new JScrollPane(table);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
p1.add(comboBox);
p1.add(new JLabel("Enter your query: "));
p1.add(queryField = new JTextField());
p1.add(new JLabel("Click here to send: "));
JButton jb = new JButton("Search");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
qtm.setHostURL();
qtm.setQuery(queryField.getText().trim());
p1.add(jb);
getContentPane().add(p1, BorderLayout.NORTH);
getContentPane().add(scrollpane, BorderLayout.CENTER);
import java.sql.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
public class QueryTableModel extends AbstractTableModel{
Vector cache;
int colCount;
String[] headers;
Connection db;
Statement statement;
String currentURL;
public QueryTableModel(){
cache=new Vector();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(Exception e){
System.out.println("problem loading the driver ");
public String getColumnName(int i){
return headers;
public int getColumnCount(){
return colCount;
public int getRowCount(){
return cache.size();
public Object getValueAt(int row, int col){
return ((String[])cache.elementAt(row))[col];
public void setHostURL(){
String url = "jdbc:odbc:VideoLibrary";
closeDB();
try{
db=DriverManager.getConnection(url,"","");
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void setQuery(String q){
cache=new Vector();
String s="select * from Product";
try{
ResultSet rs=statement.executeQuery(q);
ResultSetMetaData meta=rs.getMetaData();
colCount=meta.getColumnCount();
headers=new String[colCount];
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);
while(rs.next()){
String[] record=new String[colCount];
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);
cache.addElement(record);
fireTableChanged(null);
catch(Exception e){
cache=new Vector();
e.printStackTrace();
public void initDB(String url){
try{
db=DriverManager.getConnection(url);
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void closeDB(){
try{
if(statement!=null){
statement.close();
if(db!=null){
db.close();
catch(Exception e){
System.out.println("Could not close the current connection.");
e.printStackTrace(); -
How to assign value from insert statement to variable from a trigger
Hi,
I got this really annoying problem and I don't know if I am doing it correctly.
I have a BEFORE INSERT trigger on a table. When someone executes an insert statement I want to grab the value of a column from that statement and assign it to a variable and then do stuff with it. I'm stuck on the assignment.. look below..
CREATE OR REPLACE TRIGGER CARS.geotest2_trigger
BEFORE INSERT ON CARS.GEO_TEST2
FOR EACH ROW
DECLARE
v_chainkey nchar(32);
v_chainkey2 nchar(32);
not_exists EXCEPTION;
BEGIN
:NEW.CHAINKEY := v_chainkey;
SELECT GEO_TEST.CHAINKEY INTO v_chainkey2 FROM GEO_TEST WHERE GEO_TEST.CHAINKEY = v_chainkey;
IF v_chainkey2 = '' or v_chainkey2 is null THEN
RAISE not_exists;
ELSE
INSERT INTO GEO_TEST2 VALUES(:NEW.CHAINKEY, :NEW.BLA, :NEW.FOO);
END IF;
EXCEPTION
WHEN not_exists THEN
RAISE_APPLICATION_ERROR(-20010, 'Chainkey does not exist in parent table GEO_TEST');
END;
I keep getting this error
Error: ORA-04098: trigger 'CARS.GEOTEST2_TRIGGER' is invalid and failed re-validation
SQLState: 42000
ErrorCode: 4098It isn't assigning because v_chainkey is not at the left hand side of the assignment statement.
test@ORA10G>
test@ORA10G>
test@ORA10G> declare
2 x number := 5;
3 y number;
4 begin
5 x := y; -- does not assign anything to y; assigns NULL to x,
6 -- because y is NULL at this point
7 -- so, essentially the value 5 of x is *LOST* now
8 dbms_output.put_line('x = '||x);
9 end;
10 /
x =
PL/SQL procedure successfully completed.
test@ORA10G>
test@ORA10G>
test@ORA10G>In any case, here's what you are probably looking for:
test@ORA10G>
test@ORA10G> --
test@ORA10G> drop table geo_test;
drop table geo_test
ERROR at line 1:
ORA-00942: table or view does not exist
test@ORA10G> drop table geo_test2;
drop table geo_test2
ERROR at line 1:
ORA-00942: table or view does not exist
test@ORA10G>
test@ORA10G> create table geo_test (chainkey nchar(32));
Table created.
test@ORA10G> insert into geo_test (chainkey) values ('a');
1 row created.
test@ORA10G> insert into geo_test (chainkey) values ('');
1 row created.
test@ORA10G>
test@ORA10G> create table geo_test2 (chainkey nchar(32), bla number(1), foo number(1));
Table created.
test@ORA10G>
test@ORA10G>
test@ORA10G> CREATE OR REPLACE TRIGGER geotest2_trigger
2 BEFORE INSERT ON GEO_TEST2
3 FOR EACH ROW
4 DECLARE
5 v_chainkey2 nchar(32);
6 not_exists EXCEPTION;
7 BEGIN
8 SELECT GEO_TEST.CHAINKEY INTO v_chainkey2 FROM GEO_TEST WHERE nvl(GEO_TEST.CHAINKEY,'~') = nvl(:new.chainkey,'~');
9 IF v_chainkey2 is null THEN
10 RAISE not_exists;
11 END IF;
12 EXCEPTION
13 WHEN not_exists THEN
14 RAISE_APPLICATION_ERROR(-20010, 'Chainkey does not exist in parent table GEO_TEST');
15 END;
16 /
Trigger created.
test@ORA10G>
test@ORA10G> --
test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values ('b',1,1);
insert into geo_test2 (chainkey,bla,foo) values ('b',1,1)
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at "TEST.GEOTEST2_TRIGGER", line 5
ORA-04088: error during execution of trigger 'TEST.GEOTEST2_TRIGGER'
test@ORA10G>
test@ORA10G> --
test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values (null,1,1);
insert into geo_test2 (chainkey,bla,foo) values (null,1,1)
ERROR at line 1:
ORA-20010: Chainkey does not exist in parent table GEO_TEST
ORA-06512: at "TEST.GEOTEST2_TRIGGER", line 11
ORA-04088: error during execution of trigger 'TEST.GEOTEST2_TRIGGER'
test@ORA10G>
test@ORA10G> --
test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values ('a',1,1);
1 row created.
test@ORA10G>
test@ORA10G>
test@ORA10G>pratz
I think the sole purpose of that "not_exists" exception is this -
If you try to insert a NULL value for GEO_TEST2.CHAINKEY, then this trigger will throw an error even if at least one NULL value exists in GEO_TEST.CHAINKEY column.
Not sure if that's something that you wanted.
Message was edited by:
pratz -
Making an exception abort the insert it triggered
I have a trigger that runs off of an insert statement. The trigger checks the fields inserted and, if necessary, throw a user-defined exception.
The exception is thrown correctly, but the insert statement is still added to the database. How can I prevent this particular statement from being inserted?Here's an example of raising a user-defined exception in the trigger and then handling that exception in the calling program and continuing:
sql>create table t (c integer);
Table created.
sql>create or replace trigger t_trg
2 before insert on t
3 for each row
4 declare
5 e_myexception exception;
6 pragma exception_init(e_myexception, -20000);
7 begin
8 if :new.c = 2 then
9 raise e_myexception;
10 end if;
11 end;
12 /
Trigger created.
sql>declare
2 e_trigger_not_happy exception;
3 pragma exception_init(e_trigger_not_happy, -20000);
4 begin
5 for i in 1..3 loop
6 begin
7 insert into t values (i);
8 exception
9 when e_trigger_not_happy then
10 null; -- continue with the loop
11 end;
12 end loop;
13 end;
14 /
PL/SQL procedure successfully completed.
sql>select * from t;
C
1
3 -
Insert statement executes before If statements
Hello All,
I am trying to validate few fields before inserting them into table.
for example:
IF params('txtID') IS NULL THEN
"SOME MSG";
ELSIF params('txtName') IS NULL THEN
"SOME MSG";
END IF;
INSERT INTO TABLE T1
VALUES(params('txtID'),params('txtName');
What I want to do is : I want to validate two fields before inserting.
Can anyone help me?
Thank you,
H.It directly executes insert statement. If I delete insert, it executes that IF statement.
It is strange.Let's be clear about this, it is not strange. Your original IF statements did execute before the INSERT but they did not raise an exception. Consequently the INSERT statement was processed. Your "SOME MSG" mechanism is obviously only triggered after the procedure completed. Walter's solution worked for you because it raise exceptions, which prevented the INSERT statement from executing.
Anyway, it is obvious that you haven't got NOT NULL enforced on your table, which is A Bad Thing. You shoudn't be enforcing such constraints through a procedure.
Cheers, APC
blog: http://radiofreetooting.blogspot.com
Edited by: APC on Feb 3, 2009 5:48 PM
Only because the OP edited their final post, and removed the lines I quoted. -
Using sql:variable in an insert statement
I'm writing an insert statement for a table with an XML column. Most of the XML is static, but I need to replace the value of an element with the value of a T-SQL variable, as shown here:
CREATE TABLE [dbo].[OrderDetail](
[OrderID] [int] NULL,
[OrderDetail] [xml] NULL
GO
DECLARE @XMLData XML;
DECLARE @ItemID INT;
SET @ItemID = 1000;
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</OrderDetail>
SET @XMLData.modify('insert <ItemID>[sql:variable("@ItemID")]</ItemID> into (/OrderDetail)[1]')
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@ItemID, @XMLData);
When I run this, it inserts "[sql:variable("@ItemID")]" instead of the value of @ItemID. If someone could show me the proper syntax, I would really appreciate it. Thanks.Yes, that worked. Now I want to change it a little. I also have an attribute that I need to update with the value of a variable.
DECLARE @XMLData XML;
DECLARE @SetID INT;
DECLARE @SetIDStr VARCHAR(12);
DECLARE @SetIDXML XML;
SET @SetID = 9999;
SET @SetIDStr = CONVERT(VARCHAR(12), @SetID);
SET @SetIDXML = CONVERT(XML, @SetIDStr);
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ItemID>1000</ItemID>
<RightOperand ID="15524" Name="ItemName" Value="15524" />
</OrderDetail>
SET @XMLData.modify('replace value of (/OrderDetail/RightOperand/@ID)[1] with sql:variable("@SetIDXML")');
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@SetID, @XMLData);
SELECT * FROM [dbo].[OrderDetail];
I'm trying to replace "ID="15524"" with the value of @SetID. This code throws an exception:
Msg 9342, Level 16, State 1, Line 23
XQuery [modify()]: An XML instance is only supported as the direct source of an insert using sql:column/sql:variable.
Thanks again for your help. -
Insert statement will not work if select statement has less number of colum
Hi,
One of my thread is already resolved on the following URL : unable to insert rows into the table
DROP TABLE TEMP;
CREATE TABLE TEMP AS SELECT * FROM CASE_101 WHERE 1=2;
DECLARE
S VARCHAR2(200);
STMT VARCHAR2(500);
begin
for C in (select TABLE_NAME INTO S from USER_TABLES where TABLE_NAME like 'CASE%' TABLE_NAME NOT like '%OLD' and Num_ROWS > 0 order by TABLE_NAME) loop
STMT := 'INSERT INTO TEMP SELECT * FROM ';
STMT:=STMT || C.TABLE_NAME;
EXECUTE IMMEDIATE STMT;
dbms_output.put_line(c.table_name);
end loop;
end;
i am facing now some different; almost all the tables have same number of columns except in few of tables have some additional columns. As above i am creating a table "TEMP" who has highest column temp(by doing some manual process). The table who has less columns than "TEMP" table : Insert statement will not work. 'INSERT INTO TEMP SELECT * FROM less_columns_table_name'.
Please let me know , how can i execute proper way.
Thanks.
Best Regards
Arshaduser13360241 wrote:
Hi,
One of my thread is already resolved on the following URL : unable to insert rows into the table
DROP TABLE TEMP;
CREATE TABLE TEMP AS SELECT * FROM CASE_101 WHERE 1=2;
DECLARE
S VARCHAR2(200);
STMT VARCHAR2(500);
begin
for C in (select TABLE_NAME INTO S from USER_TABLES where TABLE_NAME like 'CASE%' TABLE_NAME NOT like '%OLD' and Num_ROWS > 0 order by TABLE_NAME) loop
STMT := 'INSERT INTO TEMP SELECT * FROM ';
STMT:=STMT || C.TABLE_NAME;
EXECUTE IMMEDIATE STMT;
dbms_output.put_line(c.table_name);
end loop;
end;
i am facing now some different; almost all the tables have same number of columns except in few of tables have some additional columns. As above i am creating a table "TEMP" who has highest column temp(by doing some manual process). The table who has less columns than "TEMP" table : Insert statement will not work. 'INSERT INTO TEMP SELECT * FROM less_columns_table_name'.
Please let me know , how can i execute proper way.
Thanks.
Best Regards
Arshadmore often than not "TEMP" tables are NOT required & are highly inefficient in Oracle.
Either only specify explicit column in TEMP to get data,
or provide value for "extra" column in TEMP -
Using sqlerrm in insert statement in 10g
Hi,
I do not have 10g to test the following snippet, which tries to use sqlerrm in an insert statement:
-- start testcase
drop table tbl;
drop table err;
create table tbl (x number);
create table err (a number, b varchar2(4000));
declare
n_tmp tbl.x%type;
begin
select x into n_tmp from tbl;
exception
when others then
-- the line below works in 9i
-- dbms_output.put_line('Sqlerrm: '||sqlerrm);
-- but the insert statement doesn't work in 9i, how about 10g ?
insert into err(a,b) values (1,sqlerrm);
commit;
end;
declare
n_tmp tbl.x%type;
begin
select x into n_tmp from tbl;
exception
when others then
-- the line below works in 9i
-- dbms_output.put_line('Sqlerrm: '||sqlerrm);
-- the insert statement works in 9iR2 but the error message is
-- not the one sought, how about 10g ?
insert into err(a,b) values (1,sys.standard.sqlerrm);
commit;
end;
/Can someone test it on any release/edition of 10g please ?
The tests on 9iR2 below behave predictably:
SQL>
SQL> @ver
BANNER
Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
PL/SQL Release 9.2.0.8.0 - Production
CORE 9.2.0.8.0 Production
TNS for Solaris: Version 9.2.0.8.0 - Production
NLSRTL Version 9.2.0.8.0 - Production
SQL>
SQL>
SQL> -- start testcase
SQL> drop table tbl;
Table dropped.
SQL> drop table err;
Table dropped.
SQL>
SQL> create table tbl (x number);
Table created.
SQL> create table err (a number, b varchar2(4000));
Table created.
SQL>
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception
6 when others then
7 -- the line below works in 9i
8 -- dbms_output.put_line('Sqlerrm: '||sqlerrm);
9 -- but the insert statement doesn't work in 9i, how about 10g ?
10 insert into err(a,b) values (1,sqlerrm);
11 commit;
12 end;
13 /
insert into err(a,b) values (1,sqlerrm);
ERROR at line 10:
ORA-06550: line 10, column 36:
PL/SQL: ORA-00984: column not allowed here
ORA-06550: line 10, column 5:
PL/SQL: SQL Statement ignored
SQL>
SQL> --
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception
6 when others then
7 -- the line below works in 9i
8 -- dbms_output.put_line('Sqlerrm: '||sqlerrm);
9 -- the insert statement works in 9iR2 but the error message is
10 -- not the one sought, how about 10g ?
11 insert into err(a,b) values (1,sys.standard.sqlerrm);
12 commit;
13 end;
14 /
PL/SQL procedure successfully completed.
SQL>
SQL> select * from err;
A B
1 ORA-0000: normal, successful completion
SQL>
SQL>The behavior of the second pl/sql block was mentioned by Nicolas:
Re: INSERT INTO ..VALUES (SQLERRM, SQLCODE, SYSDATE) doesn't work?
Is there any change in 10g ?
Thanks in advance,
pratz
(Sorry, the hyperlink is getting modified automatically; remove the backslash ("\") immediately before the ampersand ("&") character.)
Message was edited by:
pratzSame in 10.2.0.3.0
SQL*Plus: Release 10.1.0.4.2 - Production on Thu Jan 24 11:55:53 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> drop table tbl;
Table dropped.
SQL>
SQL> drop table err;
Table dropped.
SQL>
SQL> create table tbl (x number);
Table created.
SQL>
SQL> create table err (a number, b varchar2(4000));
Table created.
SQL> declare
2 n_tmp tbl.x%type;
3 begin select x into n_tmp from tbl;
4 exception when others then
5 -- the line below works in 9i
6 --dbms_output.put_line('Sqlerrm: '||sqlerrm);
7 -- but the insert statement doesn't work in 9i, how about 10g ?
8 insert into err(a,b) values (1,sqlerrm);
9 commit;
10 end;
11 /
insert into err(a,b) values (1,sqlerrm);
ERROR at line 8:
ORA-06550: line 8, column 32:
PL/SQL: ORA-00984: column not allowed here
ORA-06550: line 8, column 1:
PL/SQL: SQL Statement ignored
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception when others then
6 -- the line below works in 9i
7 --dbms_output.put_line('Sqlerrm: '||sqlerrm);
8 -- the insert statement works in 9iR2 but the error message is -- not the one sought, how a
bout 10g ? i
9 insert into err(a,b) values (1,sys.standard.sqlerrm);
10 commit;
11 end;
12 /
PL/SQL procedure successfully completed.
SQL> select * from err;
A
B
1
ORA-0000: normal, successful completion
SQL> -
Plsql insert statement. urgent help needed
Hi all oracle gurus
I am trying to insert a value which is difference between two dates, for that reason i am doing (" rec_jag_promos.end_date -rec_jag_promos.start_date") inside my insert statement.
but it is not working. my plsql code is running but not giving me any o/p.
Here what i am trying to do is i want to insert DAYS value into my table which is between start date and end date.
........its not working . please guide me or correct me.
Below is part of my querry ........
Thanks
-- migrate data
FOR rec_jag_promos IN cur_jag_promos
LOOP
v_jag_count := v_jag_count + 1;
BEGIN
v_wots_hot_id := rec_jag_promos.promotion_id;
-- this call will throw and exception 0 or many regions found
v_region_id := get_region_id( rec_jag_promos.promotion_id, rec_jag_promos.region_display_type );
INSERT INTO wotif_promo.WOTS_HOT
( id, country_code,
start_date, end_date,inventory_source_id,hotel_id,
rate_plan_code,region_id,blurb, modified_username,
version,DAYS_ACTIVE )
VALUES
( v_wots_hot_id, rec_jag_promos.country_code,
rec_jag_promos.start_date, rec_jag_promos.end_date,v_inv_source_id,rec_jag_promos.hotel_id,
rec_jag_promos.rate_plan_code, v_region_id, rec_jag_promos.blurb, rec_jag_promos.modified_username,
1, rec_jag_promos.end_date-rec_jag_promos.start_date);
v_wots_hot_inserts := v_wots_hot_inserts + 1;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'WOTS_HOT Insert Error on wots_hot_id : ' || rec_jag_promos.wots_hot_id );
DBMS_OUTPUT.PUT_LINE( SQLCODE || ' ' || SQLERRM );
v_wots_hot_errs := v_wots_hot_errs + 1;
END;I am trying to insert a value which is difference between two dates, for that reason i am doing (" rec_jag_promos.end_date -rec_jag_promos.start_date") inside my insert statement.
........its not working . please guide me or correct me.
Below is my file ........
Thanks
DECLARE
-- cursors
CURSOR cur_inventory_source IS
select id
from wotif_common.inventory_source
where SHORT_DESCRIPTION = 'wotif';
CURSOR cur_jag_promos IS
select wh.id as wots_hot_id, p.id as promotion_id, cty.iso_countrycode as country_code,
wh.blurb, dm.propid as hotel_id,
p.startdts as START_DATE, p.expirydts as END_DATE,
wa.username as modified_username, rt.roomtypecode as rate_plan_code,
dm.dealdate as hot_date, dm.advertisedrate as price,
wh.REGIONDISPLAYTYPE as region_display_type
from wotif_web.PROM_wots_hot wh
join wotif_web.PROMOTION p on wh.promotionid=p.id
join wotif_web.country cty on p.countrycode=cty.countrycode
join wotif_web.deal_master dm on wh.dealid=dm.dealid
join wotif_web.prop_master_room_type rt on rt.proproomtypeid=dm.proproomtypeid
join wotif_web.wotif_administrator wa on p.adminid = wa.administratorid
where p.expirydts < trunc(sysdate) ---> TRUNC(sysdate)
order by wh.id;
-- variables
v_debug BOOLEAN := FALSE;
v_nls_length_semantics VARCHAR2(255);
v_jag_count INTEGER := 0;
v_inv_source_id WOTIF_COMMON.INVENTORY_SOURCE.ID%TYPE;
v_wots_hot_id WOTIF_PROMO.WOTS_ON.ID%TYPE;
v_wots_hot_day_id WOTIF_PROMO.WOTS_ON_DAY.ID%TYPE;
v_wots_hot_inserts INTEGER := 0;
v_wots_hot_day_inserts INTEGER := 0;
v_wots_hot_errs INTEGER := 0;
v_wots_hot_rate_plan_errs INTEGER := 0;
v_wots_hot_day_errs INTEGER := 0;
v_region_id wotif_promo.WOTS_HOT.region_id%TYPE;
-- variables
FUNCTION get_region_id
p_promotion_id IN wotif_web.PROMOTION.id%TYPE,
p_region_type_enum IN wotif_web.PROM_WOTS_HOT.regiondisplaytype%TYPE
) RETURN NUMBER
IS
CURSOR cur_sub_region
p_promotion_id IN wotif_web.PROMOTION.id%TYPE,
p_region_type IN wotif_web.PROPERTY_REGION.region_type%TYPE
) IS
select reg.region_id as REGION_ID
from wotif_web.PROM_WOTS_HOT wh
join wotif_web.PROPERTY_REGION reg on wh.propid = reg.prop_id
where wh.promotionid = p_promotion_id
and reg.region_type = p_region_type;
CURSOR cur_region
p_promotion_id IN wotif_web.PROMOTION.id%TYPE,
p_region_type IN wotif_web.PROPERTY_REGION.region_type%TYPE
) IS
select NVL(reg.parent_id, reg.id) as REGION_ID
from wotif_web.PROM_WOTS_HOT wh
join wotif_web.PROPERTY_REGION prop_reg on wh.propid = prop_reg.prop_id
join wotif_web.region reg on prop_reg.region_id = reg.id
where wh.promotionid = p_promotion_id
and prop_reg.region_type = p_region_type;
v_region_id wotif_web.PROPERTY_REGION.region_id%TYPE;
BEGIN
-- if region A
IF p_region_type_enum = 0
THEN
OPEN cur_region( p_promotion_id, 'A' );
FETCH cur_region INTO v_region_id;
CLOSE cur_region;
END IF;
-- if region B
IF p_region_type_enum = 2
THEN
OPEN cur_region( p_promotion_id, 'B' );
FETCH cur_region INTO v_region_id;
CLOSE cur_region;
END IF;
-- if sub_region A
IF p_region_type_enum = 1
THEN
OPEN cur_sub_region( p_promotion_id, 'A' );
FETCH cur_sub_region INTO v_region_id;
CLOSE cur_sub_region;
END IF;
-- if sub_region B
IF p_region_type_enum = 3
THEN
OPEN cur_sub_region( p_promotion_id, 'B' );
FETCH cur_sub_region INTO v_region_id;
CLOSE cur_sub_region;
END IF;
RETURN v_region_id;
END get_region_id;
-- main block
BEGIN -- outer block
-- initialise
DBMS_OUTPUT.enable( 1000000 );
-- validate
EXECUTE IMMEDIATE 'alter session set NLS_LENGTH_SEMANTICS = ''CHAR''';
SELECT VALUE
INTO v_nls_length_semantics
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_LENGTH_SEMANTICS';
DBMS_OUTPUT.put_line('nls length semantics: ' || v_nls_length_semantics);
IF v_nls_length_semantics 'CHAR' THEN
RAISE_APPLICATION_ERROR( -20005, 'PROMO_MIGRATION ERROR: NLS_LENGTH_SEMANTICS set incorrectly');
END IF;
OPEN cur_inventory_source;
FETCH cur_inventory_source INTO v_inv_source_id;
CLOSE cur_inventory_source;
DBMS_OUTPUT.put_line('v_inv_source_id: ' || v_inv_source_id);
IF v_inv_source_id IS NULL THEN
RAISE_APPLICATION_ERROR( -20005, 'PROMO_MIGRATION ERROR: v_inv_source_id not set');
END IF;
-- migrate data
FOR rec_jag_promos IN cur_jag_promos
LOOP
v_jag_count := v_jag_count + 1;
BEGIN
v_wots_hot_id := rec_jag_promos.promotion_id;
-- this call will throw and exception 0 or many regions found
v_region_id := get_region_id( rec_jag_promos.promotion_id, rec_jag_promos.region_display_type );
INSERT INTO wotif_promo.WOTS_HOT
( id, country_code,
start_date, end_date,inventory_source_id,hotel_id,
rate_plan_code,region_id,blurb, modified_username,
version,DAYS_ACTIVE )
VALUES
( v_wots_hot_id, rec_jag_promos.country_code,
rec_jag_promos.start_date, rec_jag_promos.end_date,v_inv_source_id,rec_jag_promos.hotel_id,
rec_jag_promos.rate_plan_code, v_region_id, rec_jag_promos.blurb, rec_jag_promos.modified_username,
*1, rec_jag_promos.end_date -rec_jag_promos.start_date);*
v_wots_hot_inserts := v_wots_hot_inserts + 1;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'WOTS_HOT Insert Error on wots_hot_id : ' || rec_jag_promos.wots_hot_id );
DBMS_OUTPUT.PUT_LINE( SQLCODE || ' ' || SQLERRM );
v_wots_hot_errs := v_wots_hot_errs + 1;
END;
-- insert single mandatory wots_hot_day
BEGIN
v_wots_hot_day_id := wotif_promo.wots_hot_day_seq.nextval;
INSERT INTO wotif_promo.wots_hot_day
( id, wots_hot_id, hot_date, price )
VALUES
( v_wots_hot_day_id, v_wots_hot_id, rec_jag_promos.hot_date, rec_jag_promos.price );
v_wots_hot_day_inserts := v_wots_hot_day_inserts + 1;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'WOTS_HOT DAYS Insert Error on wots_hot_id : ' || rec_jag_promos.wots_hot_id );
DBMS_OUTPUT.PUT_LINE( SQLCODE || ' ' || SQLERRM );
v_wots_hot_day_errs := v_wots_hot_day_errs + 1;
END;
END LOOP; -- wots_hot loop
DBMS_OUTPUT.PUT_LINE( 'Jaguar wots hot count ' || NVL( v_jag_count,0) );
DBMS_OUTPUT.PUT_LINE( 'WOTS_HOT' );
DBMS_OUTPUT.PUT_LINE( 'inserts ' || NVL( v_wots_hot_inserts,0) );
DBMS_OUTPUT.PUT_LINE( 'errors ' || NVL( v_wots_hot_errs,0) );
DBMS_OUTPUT.PUT_LINE( ' ' );
DBMS_OUTPUT.PUT_LINE( 'WOTS_HOT_DAY' );
DBMS_OUTPUT.PUT_LINE( 'inserts ' || NVL( v_wots_hot_day_inserts,0) );
DBMS_OUTPUT.PUT_LINE( 'errors ' || NVL( v_wots_hot_day_errs,0) );
DBMS_OUTPUT.PUT_LINE( ' ' );
END; --outer block
commit;
select count(*) from wotif_promo.wots_hot;
select count(*) from wotif_promo.wots_hot_day;
select * from wotif_promo.wots_hot_day;
--commit;
--rollback; -
Exception Raised error, not sure how to fix it.
So I bought this game, Dragon age origins, and I try to launch the application. When I do, I get this error " Exception raised,
Unhandled page fault on read access to 0x00000038 at address 0x0088d374.
Do you wish to debug it ?"
It has a Yes and a No. Clicking yes has the application shut down, and No justs leaves me with a black screen.
I was wondering if there's a general way to get rid of this error.Could be many things, we should start with this...
"Try Disk Utility
1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at the top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.
3. Click the First Aid tab.
4. Select your Mac OS X volume.
5. Click Repair. Disk Utility checks and repairs the disk."
http://docs.info.apple.com/article.html?artnum=106214
Then try a Safe Boot, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, reboot when it completes.
(Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive.)
Then...
One way to test is to Safe Boot from the HD, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, Test for problem in Safe Mode...
PS. Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive
Reboot, test again.
If it only does it in Regular Boot, then it could be some hardware problem like Video card, (Quartz is turned off in Safe Mode), or Airport, or some USB or Firewire device, or 3rd party add-on, Check System Preferences>Accounts (Users & Groups in later OSX versions)>Login Items window to see if it or something relevant is listed.
Check the System Preferences>Other Row, for 3rd party Pref Panes.
Also look in these if they exist, some are invisible...
/private/var/run/StartupItems
/Library/StartupItems
/System/Library/StartupItems
/System/Library/LaunchDaemons
/Library/LaunchDaemons -
need help urgently,am useing microsoft access as my database,whenever i try to insert data into the table i have in my database it tells me syntax error in INSERT INTO statement.please how do i overcome this problem.my code is below.thanks in advance.
'\n'
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewCustomerRecord extends JFrame{
private JTextField firstnameF,othernameF,phoneF,addressF,depositF,currentF,dateF;
private JButton registerbutton;
private Connection con;
private Statement st;
private ResultSet set;
private PreparedStatement stat;
public NewCustomerRecord(){
//super(f,"",true);
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel firstL = new JLabel("First Name:");
firstL.setBounds(5,15,80,20);
panel.add(firstL);
firstnameF = new JTextField();
firstnameF.setBounds(70,15,100,20);
panel.add(firstnameF);
JLabel otherL = new JLabel("Other Names:");
otherL.setBounds(175,15,80,20);
panel.add(otherL);
othernameF = new JTextField();
othernameF.setBounds(255,15,100,20);
panel.add(othernameF);
JLabel phoneL = new JLabel("Phone No.:");
phoneL.setBounds(5,40,80,20);
panel.add(phoneL);
phoneF = new JTextField();
phoneF.setBounds(70,40,100,20);
panel.add(phoneF);
JLabel addressL = new JLabel("Address:");
addressL.setBounds(185,40,80,20);
panel.add(addressL);
addressF = new JTextField();
addressF.setBounds(255,40,100,20);
panel.add(addressF);
JLabel depositL = new JLabel("Deposit:");
depositL.setBounds(5,65,60,20);
panel.add(depositL);
depositF = new JTextField();
depositF.setBounds(70,65,100,20);
panel.add(depositF);
/*JLabel currentL = new JLabel("Current Bill:");
currentL.setBounds(135,65,80,20);
panel.add(currentL);
currentF = new JTextField();
currentF.setBounds(205,65,50,20);
panel.add(currentF);*/
JLabel dateL = new JLabel("Date:");
dateL.setBounds(185,65,50,20);
panel.add(dateL);
dateF = new JTextField();
dateF.setBounds(255,65,100,20);
panel.add(dateF);
registerbutton = new JButton("Register Customer");
registerbutton.setBounds(115,100,145,20);
registerbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
insertRecord();
dispose();
registerbutton.setMinimumSize(new Dimension(50,20));
panel.add(registerbutton);
add(panel);
setSize(400,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void insertRecord(){
double bal=0.0;
String s=depositF.getText();
double dep = Double.parseDouble(s);
bal+=dep;
//String ss=dateF.getText();
//short dd=Short.parseShort(ss);
String ss=Double.toString(dep);
String bb=Double.toString(bal);
String fullName=firstnameF.getText()+"\t"+othernameF.getText();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:sparkletransaction","","");
String insert="INSERT parsonaltransaction(date,name,phone,addres,deposit,balance)";
insert=insert+" VALUES(?,?,?,?,?,?)";
stat=con.prepareStatement(insert);
stat.setString(1,dateF.getText());
stat.setString(2,fullName);
stat.setString(3,phoneF.getText());
stat.setString(4,addressF.getText());
stat.setString(5,ss);
stat.setString(6,bb);
stat.executeUpdate();
stat.close();
catch(Exception e){
System.out.println(e);
public static void main(String[] arg){
new NewCustomerRecord().setVisible(true);
}try changing
"INSERT parsonaltransactionto
"INSERT INTO parsonaltransactionEdit: Also, should that really be parsonal, or maybe personal, or maybe even personnel? -
I am having a problem. I would like to insert some form data into a database using jsp but I have coded it and it gives me an error insert statement syntax is incorrect here is my code
<%@page import="java.sql.*"%>
<html>
<head>
<title>
</title>
</head>
<body>
<%
String _driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String _url = "jdbc:odbc:testdata";
try {
Class.forName (_driver);
String dataSourceName = _url;
String dbURL = dataSourceName;
Connection con = DriverManager.getConnection(dbURL);
Statement s = con.createStatement();
String insert;
insert = "insert into order (field1 , field2 , field3) values ('"
+ request.getParameter("item1") + "' , '" + request.getParameter("item2") + "' , "
+ "'" + request.getParameter("item3") + "')";
out.print(insert);
s.execute(insert);
s.close();
con.close();
} // closes try statement
catch (Exception err) {
out.print("ERROR: " + err);
}; // closes catch statement
%>
<a href="shoppingcart.jsp">go back to shopping cart</a>
</body>
</html>here is the error it gives me
ERROR: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
the insert statement looks right to me but there is something wrong anyone got any ideas. Thanxs in advance.AAAHHHH. Order is a reserved word and that was what my table was named. I suppose because of the order by clause it is. Figures spend hours staring at it and it is right there. I have to start using prefixes and suffixes on my code it would save me so much hassel.
-
Insert statement is not executing.....
From below procedure the insert statement is not executing....
update statement is working perfectly but insert......
create or replace PROCEDURE PAYMENT(AMT NUMBER,UID NUMBER) IS
AMT1 NUMBER;
AMT NUMBER;
PD VARCHAR2(100);
C1 NUMBER;
PER NUMBER;
ACC1 VARCHAR2(15);
CF NUMBER;
CRF NUMBER;
ACC2 VARCHAR2(15);
begin
SELECT PAY_DESC INTO PD FROM SUB.PAYMENT_TY WHERE ORD=0;
SELECT NVL(AMOUNT,0) INTO C1 FROM FOOD.MEMBER WHERE LTRIM(RTRIM(UPPER(NAME))) LIKE
LTRIM(RTRIM(UPPER(PD)))
AND USER_ID=UID;
IF NVL(C1,0)>AMT THEN /*CASH*/
C1:=C1-AMT;
SELECT ACCOUNT_CODE INTO ACC1 FROM SUB.MASTER WHERE PAY_CODE=2;
INSERT INTO ACC(AMOUNT_TD,ACC_CODE,EN_DATE,FO_TYPE,PART) VALUES(AMT,ACC1,SYSDATE,'JV','CASH
PERCENTAGE FOR '||45457);
STANDARD.COMMIT;STANDARD.COMMIT;STANDARD.COMMIT;
UPDATE FOOD.MEMBER_DET SET AMOUNT=C1 WHERE USER_ID=UIDAND C_COD=2;
STANDARD.COMMIT;STANDARD.COMMIT;STANDARD.COMMIT;
END IF;
end;the values receiving in insert statement is correct values.
how to resolve this?
Thanks skud...Check for too many rows or no data found exception.
And also check the number of rows either inserted or updated.
Something like this:
create or replace PROCEDURE PAYMENT(AMT NUMBER,UID NUMBER) IS
AMT1 NUMBER;
AMT NUMBER;
PD VARCHAR2(100);
C1 NUMBER;
PER NUMBER;
ACC1 VARCHAR2(15);
CF NUMBER;
CRF NUMBER;
ACC2 VARCHAR2(15);
begin
begin
SELECT PAY_DESC
INTO PD
FROM SUB.PAYMENT_TY
WHERE ORD=0;
exception
when too_many_rows then
dbms_output.put_line('Too many rows in first SELECT');
when no_data_found then
dbms_output.put_line('No data found in first select');
end;
begin
SELECT NVL(AMOUNT,0)
INTO C1
FROM FOOD.MEMBER
WHERE LTRIM(RTRIM(UPPER(NAME))) LIKE LTRIM(RTRIM(UPPER(PD)))
AND USER_ID=UID;
exception
when too_many_rows then
dbms_output.put_line('Too many rows in second SELECT');
when no_data_found then
dbms_output.put_line('No data found in second select');
end;
IF NVL(C1,0)>AMT THEN /*CASH*/
C1:=C1-AMT;
begin
SELECT ACCOUNT_CODE
INTO ACC1
FROM SUB.MASTER
WHERE PAY_CODE=2;
exception
when too_many_rows then
dbms_output.put_line('Too many rows in third SELECT');
when no_data_found then
dbms_output.put_line('No data found in third select');
end;
INSERT INTO ACC(AMOUNT_TD,ACC_CODE,EN_DATE,FO_TYPE,PART) VALUES(AMT,ACC1,SYSDATE,'JV','CASH PERCENTAGE FOR '||45457);
dbms_output.put_line('Insert ' || sql%rowcount);
COMMIT;
UPDATE FOOD.MEMBER_DET SET AMOUNT=C1 WHERE USER_ID=UIDAND C_COD=2;
dbms_output.put_line('Update ' || sql%rowcount);
commit;
END IF;
end;
/UNTESTED!! -
Use of the "updlock" hint with update and insert statements
I have inherited some stored procedures and am trying to figure out why the developers decided to use the "updlock" hint on many of the update and insert statements. I have looked around everywhere and have found only one explanation of why "update...with
(updlock)" can be useful, namely when a table has no clustered index:
http://www.sqlnotes.info/2012/10/10/update-with-updlock/ I have found nothing yet that mentions why "insert into...with (updlock)" might be used. I understand why the hint
might be useful on select statements in some cases, but if all of the tables have clustered indexes, is there any good reason to use it on update and insert statements?
Thanks,
Ron
Ron RiceThis form of deadlock error can occur on a table which has a clustered index.
If you are doing updates on a table which has a clustered index and that table also has a nonclustered index and the nonclustered index is used to find the row to update you can see this type of deadlock. For example create a table with a clustered
primary key index and a nonclustered index by running
Create Table Foo(PK int primary key identity, OtherKey varchar(10), OtherData int);
go
Insert Foo Default Values;
go 10000
Update Foo Set OtherKey = 'C' + Cast(PK As varchar(10))
Create Unique Index FooIdx On Foo(OtherKey);
That creates a table with 10000 rows, a clustered index and a nonclustered index. Then run
Begin Transaction
Update Foo Set OtherData = 1 Where OtherKey = 'C5'
That will use the FooIdx index to find the row that needs to be updated. It will get a U lock on the index row in the FooIdx index, then an X lock on the row in the clustered index, update that row, then free the U lock on FooIdx, but keep the X lock
on the row in the clustered index. (There is other locking going on, but to simplify things, I'm only showing the locks that lead to the deadlock).
Then in another window, run
Begin Transaction
Update Foo Set OtherData = 2 Where OtherKey = 'C5'
This will get a U lock on the index row in the FooIdx index, then try to get an X lock on the row in the clustered index. But that row is already exclusively locked, so this second window will wait holding a U lock on FooIdx row and is waiting for
an X lock on the clustered index row.
Now go back to the first window and run
Update Foo Set OtherData = 3 Where OtherKey = 'C5'
This will once again try to get the U lock on the FooIdx row, but it is blocked by the U lock the second window holds. Of course the second window is blocked by the X lock on the clustered index row and you have a deadlock.
All that said, I certainly do not routinely code my updates with UPDLOCK. I try to design databases and write code so that deadlocks will be rare without holding excessive locks. The more locks you hold and the longer you hold them, the more
blocking you will get and the slower your system will run. So I write code that if a deadlock exception occurs, it is properly handled. Then if too many deadlocks occur, that is the time to go back to the code to see what changes are needed to
decrease the number of deadlocks (one way to do that may be to get locks earlier and/or hold them longer.
But I wouldn't worry much about this form of deadlock. It is, in my experience, vary rare. I don't recall ever seeing it in a production environment.
Tom
Maybe you are looking for
-
My left click does not work on my track pad on my macbook pro 13 inch, is there a fix
my left click does not work on my track pad on my macbook pro 13 inch, is there a fix
-
Hi experts, I am facing a problem regarding the output display of ABAP Query that I have created using SAP List Viewer. I have used logical database VFV in the query and some selection fields and some additional fields also. The output is shown to me
-
Mac mini not keeping connection with Cisco wireless access point
I am trying to get my wife's Mac Mini to keep it's connection with the wireless network at her school. They are using a Cisco access point (not sure of the model) which works fine with my G4 Powerbook and the numerous Macbooks being used there, but f
-
Hello All I am working on CRM 5.0 service module Can I create a service order with more than one service I mean one document but contains multiple services and assign each service to a person responsible? And how? Thanks in advance Regards Jacopo Fra
-
Platform swat from CS5 PC to Mac
Hi. My name is Camilla. I´m from Sweden so maybe my English isn´t the best. I have a question. I bought Photoshop CS5 with licens for 2 PC. I´m only using one. Now I will buy a Mac instead. I want to do a platform swat from PC to Mac. I need to run b