Populating primary key from My SQL
I have a table called MEMBERS in MY SQL with BEFORE INSERT trigger on it to create the primary key. Trigger works when I use the MYSQL prompt to insert. By Using BC in 10.1.3 , I want to populate the primary key (memberid) when insert any record in to this table. In the model, 'primary key','& TRansient' are the only properties selected for the entity.
When I insert using BC the record in not being created. How do I make it work.
Following is the trigger on the table.
CREATE OR REPLACE TRIGGER ASSIGN_MEM_ID
BEFORE INSERT ON MEMBERS FOR EACH ROW
BEGIN
IF :NEW.MEMBERID IS NULL OR :NEW.MEMBERID < 0 THEN
SELECT memid
INTO :NEW.MEMBERID
FROM MemberSequence;
UPDATE MemberSequence
SET memid= memid+1;
END IF;
END;
Any help is appreciated.
Thanks
nk
Try using the DBSequence data type for the column.
see "6.6.3.8 Trigger-Assigned Primary Key Values from a Database Sequence" in the ADF Developer Guide.
http://download.oracle.com/docs/html/B25947_01/bcentities006.htm#sm0147
Similar Messages
-
Difference in Triggers for populating Primary Keys
version: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
Hello,
I have a question regarding using Triggers to populate Primary Keys.
One Trigger I've seen written like this:
CREATE OR REPLACE TRIGGER "BI_MY_TABLE"
BEFORE INSERT
ON my_table
FOR EACH ROW
BEGIN
IF :new."MY_TABLE_ID" IS NULL THEN
SELECT "MY_TABLE_SEQ".NEXTVAL INTO :new."MY_TABLE_ID" FROM DUAL;
END IF;
END;
And another Trigger written like this:
CREATE OR REPLACE TRIGGER "BI_MY_TABLE"
BEFORE INSERT
ON my_table
FOR EACH ROW
BEGIN
FOR c1 IN (SELECT my_table_seq.NEXTVAL next_val FROM dual)
LOOP
:new.my_table_id := c1.next_val;
END LOOP;
END;
The first version is using an IF statement and the second version is using a LOOP.
My questions are:
Is there really any difference in the technique used to create the Trigger?
Is there any "benefit" in using one technique over the other?
Is there a more preferred method/technique to populating Primary Key columns?
Thanks,
JoeHi, Joe,
The second way (using a loop) is just silly. Don't use a loop.
Starting in Oracle 11, you don't need to use dual at all; you can do it like this:
CREATE OR REPLACE TRIGGER BI_MY_TABLE
BEFORE INSERT
ON my_table
FOR EACH ROW
BEGIN
IF :new.MY_TABLE_ID IS NULL THEN
:new.MY_TABLE_ID := MY_TABLE_SEQ.NEXTVAL;
END IF;
END BI_MY_TABLE; -
I have a table which has 3 foreign keys, two of which form the primary key.
I have: ID_Product, ID_Sale, ID_Buy, and also an attribute which tells if its a buy or a sale.
So, if a sale is made, the primary key should consist of ID_Product && ID_Sale, otherwise, it's ID_Product && ID_Buy.
Is there a way to do this in Oracle, and if there is, can you point me to where I can read about this?
thank you in advancetashe,
This is the wrong forum for you question. Try posting here:
PL/SQL
I will say, however, that there are advantages to keeping your primary keys apart from your data - just populating them from a sequence. Also, you may be temped to enforce this via triggers, but read the following first:
http://tkyte.blogspot.com/2008/05/another-of-day.html
Not that you would have a mutating table problem, but the two table solution may help you. Really think the design through.
Regards,
Dan -
ADF BC Primary key generation with SQL Server DB
Hi,
I am using ADF 11.1.1.6 to develop a small application that will do some very basic CRUD operations on a SQL Server DB.
I read through http://www.oracle.com/technetwork/developer-tools/jdev/multidatabaseapp-085183.html before I'm starting to implement the Entity objects.
This document describes a way to do primary key generation using a table created in the DB and instructs to create an application connection to the Database :
+2. Create a Connection to the Table+
In your application, create a database connection named ROWIDAM_DB that points to the database containing your S_ROW_ID table. Alternatively, edit your BC project's properties and add the following Java option to the project's run configuration:
-Djbo.rowid_am_conn_name= appconnection
where appconnection is the name of a database connection that points to the S_ROW_ID table.
My question is how do we do this when we mve to a production environment ?
Also I'll be interested to hear if anyone has any pointers for developing ADF apps with SQL Server. (gotchas, performance pitfalls etc. )
-Jeevan
Upadte : This is SQL Server 2005
Edited by: Jeevan Joseph on May 2, 2012 9:04 AMmy apologies to everyone ... This should have been very simple. I just need to provide the config in my AM configuration(bc4j.xml)
jbo.rowid_am_conn_name* should be set to the connection name you create. For production deployments, theres a similar
jbo.rowid_am_datasource_name* that should work just fine (though I havent tried if it has any hiccups).
I'd like to point out one thing though, for whoever might stumble upon this thread and find it useful later on...
After I did the steps above, everything seemed to work when I tested the app from the AM tester. But when I built a UI for it in ADF Faces, I started getting an exception on Create/CreateInsert :
java.lang.ClassCastException: com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to oracle.jdbc.OracleConnection
at oracle.jbo.server.OracleSQLBuilderImpl.setSessionTimeZone(OracleSQLBuilderImpl.java:5533)
at oracle.jbo.server.DBTransactionImpl.refreshConnectionMetadata(DBTransactionImpl.java:5311)
at oracle.jbo.server.DBTransactionImpl.initTransaction(DBTransactionImpl.java:1194)
at oracle.jbo.server.DBTransactionImpl.initTxn(DBTransactionImpl.java:6826)
at oracle.jbo.server.DBTransactionImpl2.connect(DBTransactionImpl2.java:136)
at oracle.jbo.common.ampool.DefaultConnectionStrategy.connect(DefaultConnectionStrategy.java:213)The trouble is that the ADF Faces adf-config.xml overrides the AM configuration. Oracle is the default, and it overrides the SQL flavor I set when initializing the Model project.
This was not mentioned in the original document probably because ADF faces was out of scope for that document.
I also found this thread extremely useful, and its what reminded me of the ADF Faces AM config overrides : Re: Locking mode 'optupdate' with SQL92
Cheers !
Jeevan -
Matching Primary key from Excel to DB Column before import
Hello Experts,
I am trying to achieve the task related with updates into my destination table via store procedure using dynamic sql. Basically I am importing the
excel file into sql server.
For further step, I want to update only the records that do not exist already in the table with reference to primary key. For this the user will provide
as an input for procedure the column (or columns) that compose the primary key in excel.
Example of EXEC command to run the store Procedure
EXEC
[ImportExcelFile_Error_Handling]
'D:\test\test.xlsx','sheet1','testDB',
'create','[Test Column1]’
So in this case the [Test Column1] from excel contains now my Primary Key and if I execute my procedure then code should check the values of the
[Test Column1] in the existing table in database, against the
[Test Column1]
in database.
If [Test Column1]
value match with db
[Test Column1]
then skip rows and if not match then insert row entry.
Below is my code, which needs to be update.
if
@TypeOfUpdate='Update'
Begin
declare
@PrimaryLeyColumn NVARCHAR(max)
set
@PrimaryLeyColumn=''
exec('Insert into ['
+ @DestinationTable
+ '] select * from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;IMEX=1;Database='
+ @TABLENAME
+ ''', ' +
''' select * from '+@SourceSheet
+ ''')')
end
thanks in advance.
Looking for support.
SharePoint_Consultant_EMEAHello,
Here is my complete code:
--------------------Declaring variables------------------------------
CREATE
PROCEDURE [dbo].[ImportExcelFile_Update_Error_Handling]
(@TABLENAME
varchar(1000)
,@SourceSheet
varchar (100)
,@DestinationTable
varchar (100)
,@TypeOfUpdate
varchar (100)
,@PrimaryLeyColumn
VARCHAR(255))
as
declare
@retval int
--Remaing Value
EXEC
master..xp_fileexist
@TABLENAME,
@retval output
-- check if file exists
if
@retval = 0
begin
print 'file does not exists.'
return
end
if
@SourceSheet is
null or @SourceSheet
= ''
set @SourceSheet
= '[Sheet1$]' -- assume that the Sheet name on excel file is the default name
else
set @SourceSheet
= '[' +
ltrim(rtrim(@SourceSheet))
+ '$]'
if
@DestinationTable is
null or
@DestinationTable =
set @DestinationTable
= substring(@SourceSheet, 2,
len(@SourceSheet)
- 3)
+ convert(varchar,
getdate(), 126)
if
@TypeOfUpdate='Update'
Begin
Begin
try
--if @PrimaryLeyColumn =''
set
@PrimaryLeyColumn =
'[]'--here i think need to add the value or updates
exec('Insert into ['
+ @DestinationTable
+ '] select * from openrowset(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;HDR=YES;IMEX=1;Database='
+ @TABLENAME
+ ''', ' +
''' select * from '+@SourceSheet
+ ''')t WHERE NOT EXISTS (SELECT 1 FROM ['
+ @DestinationTable
+ '] WHERE ['
+ @PrimaryLeyColumn
+ '] = t.[' +
@PrimaryLeyColumn +
declare
@Appendcount INT
declare
@SQLStringCount nvarchar(500);
declare
@ParamDef nvarchar(500);
declare
@TabName nvarchar(500);
SET
@SQLStringCount =
N'SELECT @COUNT=COUNT(1) FROM '+
@DestinationTable;
SET
@ParamDef =
N'@TABLE varchar(30),@COUNT BIGINT OUTPUT';
EXECUTE
sp_executesql @SQLStringCount,
@ParamDef ,@Table=@TabName,
@COUNT=@Appendcount
OUTPUT;
--Getting the rowcount as a output parameter from the sp_executesql.
if
@Appendcount != 0
PRINT
'Database is "Updated" with total number of Records= '
+ Cast(@Appendcount
AS VARCHAR(200))
end
try
Begin
Catch
if @DestinationTable is null or @DestinationTable = ''
DECLARE
@ErrorNumberUT INT
= ERROR_NUMBER();
DECLARE
@ErrorMessageofUpdateTable
NVARCHAR(max)
= ERROR_MESSAGE();
PRINT
'Error, Table not exists in the database'
PRINT
'Actual error number: ' +
CAST(@ErrorNumberUT
AS VARCHAR(10));
PRINT
'Actual Error Message: '
+ CAST(@ErrorMessageofUpdateTable
AS VARCHAR(max));
end
Catch
end
To execute this code I am using this script
EXEC
[ImportExcelFile_Update_Error_Handling]
'D:\TestFiles\Test_Updates.xlsx','sheet1','Error_Handing','update','[SUPLR_DUNS_NBR]';
[SUPLR_DUNS_NBR] is the column where I have "ID to match" with new and old content in my excel and if this content same in my sql table then skip else insert the row.
Any support in this would ge really helpful to achive my tasks goal.
thanks
SharePoint_Consultant_EMEA -
How to pass the primary key from a report to multiple forms
I am trying to build an application that tracks a person's training records. I have a report and 3 forms (all tabbed). From the report I can click the edit link to modify a person. Is there a way I can pass the primary key of the person (from the report) to the other forms? Hope what I'm trying to do is clear.
Thanks.Hi,
You can specify items from other pages also.
Did you use that popup to pick item ?
Did you noticed that it filter by page where your link point. You can remove filter from popup and then select other items.
Or just manually type your item names
Br, Jari
Edited by: jarola on Nov 11, 2009 1:08 AM -
Primary Key from Database Sequence
Hi,
I have a form that has a master block(single_record) and a child block(multi-record). I am using Database Sequence for primary key. And I am not using any toolbar, instead using the default from FORMS. I want to keep this primary key field invisible and non-navigable.
Which triggers should I write the sequence.nextval code in the form ??
Thanks!!
ShaluThanks so much!! I'll try that!!
I hope I won't get this error: it doesn't let me come out from the field unless i enter a value, because being primary it is mandatory, though i want the field to be non-navigable and i'll turn the display to false.
Thanks Again!!
Shalu -
ON UPDATE CASCADE and Autoincrement primary key with Oracle SQL Developer
hello everybody,
I want to know if Oracle SQL Developer manage autoincrement on primary key and "ON UPDATE CASCADE" when i migrate (with data) SQL Server database in Oracle database.
Can you help me ?
Thanks for your suggestions.Obtain the value of the auto increment key with the getGeneratedKeys() method.
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTable");
stmt.executeUpdate(
"CREATE TABLE autoIncTable ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
stmt.executeUpdate(
"INSERT INTO autoIncTable (dataField) "
+ "values ('data field value')",
Statement.RETURN_GENERATED_KEYS);
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
rs.close(); -
Getting the primary key from order form
Does anyone know how to get the primary key (DocEntry) off of the order form for an existing order? I don't really want to use the DocNum field since it is not the primary key and theoretically two different orders could have the same DocNum. Thanks in advance for your help.
Hi Joe,
DocEntry and DocNum values are unique, so you cannot have in db 2 orders with the same DocNum. It's possible, that DocEntry and DocNum values can vary.
If you know the DocNum value (f.e. from Order's Form), you can simple use RecordSet object:
Dim sQuery as String
Dim oOrder as SAPbobsCOM.Documents
Dim oRecordSet As SAPbobsCOM.Recordset
Set oOrder = oCompany.GetBusinessObject(oOrders)
Set oRecordSet = oCompany.GetBusinessObject(BoRecordset)
sQuery = "Select DocEntry From ORDR Where DocNum = '" & DocNumber & "'"
oRecordSet.doQuery sQuery
If oRecordSet.RecordCount > 0 Then
oOrder.GetByKey(oRecordSet.Fields(0).Value)
End If
And this should work.
Regards
Libor. -
Hi ,
I want to get the Primary Keys for my tables . I used
java.sql.DatabaseMetaData databasemetadata = connection.getMetaData();
ResultSet rs = databasemetadata.getTables(null, null, "%", null);
rs.next();
System.out.println(" TABLE_CAT "+ rs.getString(1));
System.out.println(" TABLE_SCHEM "+rs.getString(2));
System.out.println(" TABLE_NAME "+rs.getString(3));
System.out.println(" TABLE_TYPE "+rs.getString(4));
System.out.println(" REMARKS "+rs.getString(5)); gives :
TABLE_CAT null
TABLE_SCHEM PROGRESS
TABLE_NAME ApplicConv
TABLE_TYPE SYNONYM
REMARKS null
Now if I use :
rs = databasemetadata.getPrimaryKeys(null,"PROGRESS","Applicconv");
System.out.println("Is result set Non empty "+rs.next());gives :
Is ResultSet non empty false .
Can you tell me why this result is empty? Is it because of my table is a Synonym?
If it is Synonym how to get the[b] primary key ?does your database documentation provide any hints?
or your jdbc driver? -
How to get the Primary key from Synonym
Hi ,
I want to get the Primary Keys for my tables . I used
java.sql.DatabaseMetaData databasemetadata = connection.getMetaData();
ResultSet rs = databasemetadata.getTables(null, null, "%", null);
rs.next();
System.out.println(" TABLE_CAT "+ rs.getString(1));
System.out.println(" TABLE_SCHEM "+rs.getString(2));
System.out.println(" TABLE_NAME "+rs.getString(3));
System.out.println(" TABLE_TYPE "+rs.getString(4));
System.out.println(" REMARKS "+rs.getString(5)); gives :
TABLE_CAT null
TABLE_SCHEM PROGRESS
TABLE_NAME ApplicConv
TABLE_TYPE SYNONYM
REMARKS null
Now if I use :
rs = databasemetadata.getPrimaryKeys(null,"PROGRESS","Applicconv");
System.out.println("Is result set Non empty "+rs.next()); gives :
Is ResultSet non empty false .
Can you tell me why this result is empty? Is it because of my table is a Synonym?
If it is Synonym how to get the primary key ?You can use DatabaseMetaData#getPrimaryKeys.
-
Retrieving auto inc primary key from entity bean (MySQL DB)
Hello,
I searched the forum intensively, but did not find an answer for the following problem.
I've set up an MySQL database "Location" with two fields (ID, Description), ID is my primary key and I've added the AUTO_INCREMENT flag to this field. This works fine, i can add a row in the table with my entity bean "Location" from my session bean :
Location l = new Location();
l.setDescription("at home");
em.persist(l);
and even when I ask this location back from the DB, there is no problem :
Location l = em.find(Location.class,1);
return l.getDescription();
The rows in the table increment nicely. The problem however is, that you don't allways know the ID. So I would like to do the following from my session bean:
Location l = new Location();
l.setDescription("at home");
em.persist(l);
int id = l.getId();
the getID method allways returns a null object. The row is added in the DB, but the auto incremented ID is not returned to the entity bean!
I know I could solve this by generating the ID's myself, but one of the strengths of autoincrement should be not to have to do this, no?
If anyone has a clue how to solve this issue, I would very much appreciate it !
Michiel
Edited by: Michiel82 on Dec 6, 2007 6:01 AMNo reactions so far ... this is a work-around for the issue :
I've created an additional table sequence with two fields: gen_key and gen_value. Then, in my Location entity bean I can add the following:
@TableGenerator(
name="locationGen",
table="sequence",
pkColumnName="gen_key",
valueColumnName="gen_value",
pkColumnValue="location",
allocationSize=1
@Id
@GeneratedValue(strategy=GenerationType.TABLE,generator="locationGen")
@Column(name = "id", nullable=false)
private Short id;
This generates the primary key in the bussiness logic, but I would like to get the autogenerated key from my MySQL database (see previous post). Is this perhaps not supported by EJB3.0?
Michiel -
Dynamically fill primary key from a second table
Hi,
IDOC-JDBC
during runtime, the primary_key of the table must be filled dynamically.
something like,
it should go to a table dyn_key and get the hightest value of the field there and add one to it and pass it to dyn_key
any idea how do i do it?
regards,
nikhil.Hello Nikhil,
You can use JDBC look up for retrieving the current Primary key value.....
Regards
Ashwin M -
Auto Populate Field in One Table with Primary Key from another table.
Greetings all,
I have created two tables. One for Root Cause which will be the based description information of an analysis. Each Root cause can have many corrective actions.
My Table structure is as follows:
RCCA TABLE:
=====================================
Column Name Data Type Nullable
RCCAID NUMBER No
DESCRIPTION VARCHAR2(4000) Yes
SUMMARY VARCHAR2(4000) Yes
OWNER VARCHAR2(4000) Yes
DATEOFINCIDENT DATE Yes
STATUS VARCHAR2(4000) Yes
CORRECTIVE ACTION TABLE
=====================================
Column Name Data Type Nullable
CAID NUMBER No
RCCAID NUMBER No
CANUMBER NUMBER Yes
CACTION VARCHAR2(4000) Yes
DATEDUE DATE Yes
COMMENTS VARCHAR2(4000) Yes
So I have a form that creates the RCCA and then I have another form that I want to feed off of the first form. My thought was that when the RCCA was created, it would open a report of the RCCA and then in another region of the page I would add corrective action form. What I am looking to do is when I press the Create Corrective Action, it will automatically populate the RCCAID in the Corrective Action Table so that it is associated directly to the RCCA. I don't want to have to have someone know what the RCCAID is from teh RCA table because they are autogenerated.
There may be a better way to do this and since I am new to APEX and to Oracle Databases, I am just going with what my logic tells me. Any assistance or thoughts would be appreciated.
Assuming there would be some type of trigger?
I will have to be able to view each RCCA and CA in a report that customers will see.
Thanks in Advance
WallyHi Debasis,
Have a look on this
Quick note on IDENTITY column in SAP HANA
Regards,
Krishna Tangudu -
How can I use the SQL to create a primary key for a existing table?
create table a(bm number,mc varchar2(20));
when the table was created,i want to make the column bm as
the primary key and my SQL is "alter table a enable primary key bm",the system show
me error,how can I write the right one?create table a(bm number,mc varchar2(20));
when the table was created,i want to make the column bm as
the primary key and my SQL is "alter table a enable primary key bm",the system show
me error,how can I write the right one? You do not have any primary key defined on your table yet, so, it does not make sense to enable it (if at all possible) !
You need to add PRIMARY KEY using something like this:
SQL> alter table a add constraint pk_a_bm primary key (bm) ;
Maybe you are looking for
-
Can't login to the store,get a blank white screen
I am running the latest Itunes, on a Mac running OS 10.5.8. I can open Itunes, but when I try to reach the store all I get is a white screen. Upon itunes shutdown a page of errors is listed as long as your arm. Any thoughts on how to fix this.
-
Not able to use collection multiple times in a jsp using logic:iterate
I have following question: I am working on a report using J2EE. I have a collection(resultset) which has 3 different types of vendors information along with other information in the collection and I want to put them into 3 different sections on my re
-
Changing profit center - segment assignment in ERP2004
Dear Experts, A customer of mine uses segments for IFRS reporting. They have been live for about 9 months, so obviously all profit centers already contain transaction data. In beginning of next year the number of segments will increase, but they do n
-
[Solved] I used RANGE UNBOUNDED FOLLOWING. But syntax error
http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#CIHCEIGA RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING. The short form of this is RANGE UNBOUNDED FOLLOWINGI used RANGE UNBOUNDED FOLLOWING. But I got syntax err
-
Password remember option ticked but will not retain password
I have just installed the latest Firefox on my new laptop. I have ticked the Remember Password box but I never get the opportunbity to save password and Firefox doesn't remember it. This happens on all sites which give the option on my other computer