PL/SQL Insert Row Assign PK Value
I try to insert a row of data into a table and assign a primary key value. I want to give the first available primary key, not only the nextval in the maxval. Is there a way to do it cleanly, or will I need to create a cursor to do? If I need to create a slider or the sequence, how do I declare it in my procedure? Do I need a sequence so that I couldn't just use a loop for? Please help - it seems such a simple thing, but it has left me speechless.CheRenee
Look at this,
SQL> Create table M_MOVIES(MOVIE_ID NUMBER not null);
Table created
SQL> Alter table M_MOVIES add constraint PROD_ID_PK primary key (MOVIE_ID);
Table altered
SQL> Insert Into M_movies
2 (Select level id_movies From dual connect by level <= 10);
10 rows inserted
SQL> Commit;
Commit complete
SQL> CREATE SEQUENCE seq_avail_id
2 START WITH 1
3 INCREMENT BY 1
4 MAXVALUE 99999999
5 /
Sequence created
SQL> INSERT INTO m_movies(movie_id) VALUES(seq_avail_id.NEXTVAL);
INSERT INTO m_movies(movie_id) VALUES(seq_avail_id.NEXTVAL)
ORA-00001: unique constraint (SYSTEM.PROD_ID_PK) violated
SQL> Drop SEQUENCE seq_avail_id;
Sequence dropped
SQL> Select max(movie_id) from m_movies;
MAX(MOVIE_ID)
-------------
10
SQL> CREATE SEQUENCE seq_avail_id
2 START WITH 11
3 INCREMENT BY 1
4 MAXVALUE 99999999
5 /
Sequence created
SQL> INSERT INTO m_movies(movie_id) VALUES(seq_avail_id.NEXTVAL);
1 row inserted
Kind regards
Christian Balz
Tags: Database
Similar Questions
-
How to insert rows in multiple tables in a sql
I want to know how to insert multiple lines in a single sql statement.
Let's insert records into the table emp and dept in a sql statement.
Thank youIt's here
SQL>l 1 insert all 2 into emp values(8888,'WADE','MANAGER',7839,'01-MAR-2008',5000,100,20) 3 into dept values(50,'MARKETING','NEW YORK') 4* select * from dual SQL> / 2 rows created.
SS
-
assign a value to a text element using the PL/SQL function body
Hello
I want to assign a value to a text element using PL/SQL function body option in the Source elements. But the below error when I try to apply it.
Source code:
declare
name varchar2 (100);
Start
If v ("P3_CREHIDD") = 'Edit' then
Select ename in the name of cpy_emp where empno = v('P3_EMPNO2');
end if;
end;
ERR-1904 unable to calculate the default item: type = computation_type = function body declare name varchar2 (100); so start v ('P3_CREHIDD') = 'Edit' and then select ename in the name of cpy_emp where empno = v('P3_EMPNO2'); end if; end;.
Thank you
David.Hello
Your body of the function doesn't return anything.
Maybe it worksdeclare l_name varchar2(100); begin if v('P3_CREHIDD') = 'Edit' then select ename into l_name from cpy_emp where empno = v('P3_EMPNO2'); end if; RETURN l_name; end;
BR, Jari
-
XQuery insert node and assign the value based on an XPATH expression
Hello
I am trying to write a function that receives an XML as input parameters and return updated XML output
-nodes are removed from the input XML code
-a node must be inserted and the node value must be 1 or 0, based on an XPATH expression
I discovered how to remove nodes, I discovered how to insert a new node, but I can not set the value of the conditionally inserted node an XPATH expression.
Here's my current procedure and below a sample of one XML of entry. I use Oracle 12 c.
CREATE OR REPLACE FUNCTION STRIP_XML ( IN_XML IN SYS.XMLTYPE ) RETURN SYS.XMLTYPE AS p_result XMLType; BEGIN select xmlquery( 'declare default element namespace "http://mad.evs.com/search"; (: :) copy $d := . modify ( delete node $d//MainCategory/@logId, delete node $d/MainCategory/@id, -- a lot more of those delete node -- insert a node, but the value 1 is conditional insert node <DMZ>1</DMZ> after $d/MainCategory/SDataSection/EventDate) return $d' passing in_xml returning content ) into p_result from dual; RETURN p_result; END STRIP_XML;
The condition for the value of is
HASPATH (//DigitalAssets/DigitalAsset [@ available = "true" and @videoFormatId = "11"] / VideoLocations/Videorental [@typeId = "8"]) then 1 else 0
It is complex because DigitalAssets/DigitalAsset is a collection. Here is an example of an XML to entry
<MainCategory xmlns="http://mad.evs.com/search" id="9" logId="3349" logType="3"> <Name>Sport</Name> <Serie id="163" externalId="557"> <TitleAKA>UCL 2006/07</TitleAKA> <DigitalAssets available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3"> <DigitalAsset available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3" videoFormatId="3"> <VideoLocations> <VideoLocation id="3" path="003349MA.mxf" typeId="1" locationId="1" priority="0"/> <VideoLocation id="3" path="003349MA.mxf" typeId="2" locationId="1" priority="0"/> <VideoLocation id="3" path="003349MA.mxf" typeId="5" locationId="1" priority="0"/> </VideoLocations> </DigitalAsset> <DigitalAsset available="true" som="20:28:49:05" dur="00:02:46:04" videoDurationMinutes="3" videoFormatId="11"> <VideoLocations> <VideoLocation id="101" path="003349MA.mpg" typeId="1" locationId="1" priority="0"/> <VideoLocation id="101" path="003349MA.mpg" typeId="2" locationId="1" priority="0"/> <VideoLocation id="101" path="003349MA.mpg" typeId="8" locationId="1" priority="0"/> </VideoLocations> </DigitalAsset> </DigitalAssets> <SDataSection xmlns="http://mad.evs.com/search"> <EventDate>2006-08-09</EventDate> <LogType>3</LogType> </SDataSection> </MainCategory>
In this case, because HASPATH expression could be set to true, the value of the added node must be 1.
Any help or advice how I should fight against that would be appreciated. I have no experience with XML and XQuery, I create my function through from trial and error of the doc.
Thanks and regards, Pierre
Hi Pierre,.
You can use the if-then-else statement, like this:
Insert the node
{
If ($d/MainCategory/DigitalAssets/DigitalAsset[@available="true' and @videoFormatId = '11'] / VideoLocations/Videorental [@typeId = '8'])
then 1
0 otherwise
}
After $d, MainCategory, SDataSection, EventDate
XSLT can be an alternative to the XQuery Update in this case.
-
MS SQL 2005: Assigning null value
For some reason any I have been finding it impossible to assign the value of '0' to the count() null result. It was easy to identify NULL values, but the assignment zero fails permanently.I have it!
The subquery is evaluated to NULL, so it just hit me to ISNULL the subquery set! Lol, wow. 4 days for that point and its that simple.
Thanks for the help Phil.
-
Dynamic SQL insert and dbms_sql.last_row_count
I write a procedure which takes a variable number of parameters, and fills a global temporary table with the results if a dynamic query. I want to know how many lines is in the TWG after insertion, made using dbms_sql.execute. With the help of dbms_sql.last_row_count seems to work, but the documentation: said http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_sql.htm#i1026354 'call this function after a FETCH_ROWS or an EXECUTE_AND_FETCH called. If called after a call to EXECUTE, then the returned value is zero.
A much simplified test case is:
I would like to know if it is OK to use last_row_count in this scenario? His behavior would change in the future, leading to misleading results. Because of the doubts I have I might have just to SELECT COUNT (*) from bc_test_gtt; to get my result, but which seems to be an unnecessary use of SQLCREATE GLOBAL temporary TABLE bc_test_gtt (col1 NUMBER(1)) ON COMMIT DELETE ROWS; DECLARE nSqlCursor PLS_INTEGER; nReturn PLS_INTEGER; sSql VARCHAR2(100); BEGIN sSql := 'INSERT INTO bc_test_gtt SELECT 1 FROM dual'; nSqlCursor := dbms_sql.open_cursor; dbms_sql.parse (nSqlCursor ,sSql ,dbms_sql.native ); nReturn := dbms_sql.execute(nSqlCursor); dbms_output.put_line(TO_CHAR(dbms_sql.last_row_count)||' last_row_count rows'); dbms_output.put_line(TO_CHAR(SQL%ROWCOUNT)||' sql%rowcount rows'); dbms_sql.close_cursor(nSqlCursor); END; / 1 last_row_count rows sql%rowcount rows select * from v$version; BANNER ________________________________________________________________________________ Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production PL/SQL Release 11.2.0.3.0 - Production CORE 11.2.0.3.0 ; Production TNS for 64-bit Windows: Version 11.2.0.3.0 - Production NLSRTL Version 11.2.0.3.0 - Production
Background: I store a copy of the contact information in a denormalised, cleaned of structure. When a user enters a new client in the request, my procedure will return duplicates potential, based on the contact information that the user entered.
Thank you
BenCertainly, the documentation last_row_count should not be used after execution. So probably not safe to rely on this behavior.
But the docs for run statement said:
>
This function executes a given cursor. This function accepts the ID number of the cursor and returns the number of rows processed. The return value is only valid for statements INSERT, UPDATE, and DELETE; for other types of statements, including the DDL, the return value is undefined and should be ignored.
...
Returns the number of rows processed
>And it's the package specification:
function execute(c in integer) return integer; -- Execute the given cursor and return the number of rows processed -- (valid and meaningful only for INSERT, DELETE or UPDATE statements; -- for other types of statements, the return value is undefined and -- should be ignored). -- Input parameters: -- c -- Cursor id number of the cursor to execute. -- Return value: -- Number of rows processed if the statement in the cursor is -- either an INSERT, DELETE or UPDATE statement or undefined otherwise. --
So it should be documented that you can simply use the value of nReturn ;-)
-
Assign a value of zero for no. selected lines
Try to find a way to assign a value to null if my account has no line.
What I have right now is:
Have tried different ways but I still get the message:CREATE OR REPLACE FUNCTION count_deductions (empno IN emp.empno%TYPE) RETURN NUMBER IS ded_count NUMBER(2); BEGIN SELECT count(deduction_amount) INTO ded_count FROM emp_deductions WHERE fk_empno = empno; EXCEPTION WHEN NO_DATA_FOUND THEN ded_count :=0; RETURN ded_count; END; /
SQL > select * from show_deduction_v where empno = 7169;
no selected line
Instead of the zero value by filling in the field.Ok. So the problem is that the view returns no rows. It has nothing to do with the service. The function returns 0 if there is no such thing as the EMPNO spent. The problem is that there is no line in the EMP with a 7169 EMPNO. This means that the function is never called.
Why do you want the view to return a row for an EMPNO that does not exist? Is there a table somewhere in the database where a 7169 EMPNO is? If so, your vision may outer join to that table.
Justin
-
How to solve the error ORA-00001 in SQL Insert?
Hi all, I need your help appreciated.
I do a plsql procedure that inserts a line according to the value of the slider, I have error oracle ORA-00001: unique constraint (constraint_name) violated.
This message may appear if a duplicate entry exists at a different level: in the RDBMS MySQL, I have the syntax IGNORES to solve this error of duplication... and in Oracle?
Thanks for your time and your advice.
Miguelitouser6317803 wrote:
How to solve the error ORA-00001 in SQL Insert?ORA-00001 means table a unique/primary key / index and you attempt to insert a row with the key value already exists in the table. I'll assume table has a primary key on COUNTRY_ID. Then modify SQL for:
SQL = "INSERT INTO COUNTRIES (COUNTRY_ID, COUNTRY_NAME, REGION_ID) SELECT"BZ","BLZ", 3 DOUBLE WHERE DOES NOT EXIST (SELECT 1 FROM COUNTRIES WHERE COUNTRY_ID ="BZ").
There is a good chance COUNTRY table also has unique key/index on COUNTRY_NAME. If so use:
SQL = "INSERT INTO COUNTRIES (COUNTRY_ID, COUNTRY_NAME, REGION_ID) SELECT"BZ","BLZ", 3 DOUBLE WHERE DOES NOT EXIST (SELECT 1 FROM COUNTRIES WHERE COUNTRY_ID = 'BZ' OR 'BLZ' = COUNTRY_NAME).
SY.
-
Assign a value to a populated table cell [in BULK]
Hi all
I have a problem by assigning a value to a populated table to COLLECT LOOSE .
I can reproduce the problem with this
And it's the anonymous PL/SQL block that gives me problems:CREATE TABLE TEST_TABLE ( value1 NUMBER, value2 NUMBER ); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1); INSERT INTO test_table VALUES(1,1);
The error isDECLARE SUBTYPE t_rec IS TEST_TABLE%ROWTYPE; TYPE records_table IS TABLE OF t_rec; elist RECORDS_TABLE; CURSOR table_cursor IS SELECT * FROM TEST_TABLE WHERE rownum <= 20; BEGIN OPEN table_cursor; FETCH table_cursor BULK COLLECT INTO elist; FOR j IN 1..elist.COUNT LOOP elist(j)(1) := elist(j)(1) +1; END LOOP; CLOSE table_cursor; END;
So they do not compile because of this line of code:ORA-06550: line 13, column 7: PLS-00308: this construct is not allowed as the origin of an assignment ORA-06550: line 13, column 7: PL/SQL: Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action:
enclose (j) (1): = enclose (j) (1) + 1;
Why it does not work?
If I try to do, works perfectly:
Published by: user10396517 on 2.35 2-mar-2012DECLARE TYPE v_num_table IS TABLE OF NUMBER; TYPE v_2_num_table IS TABLE OF v_num_table; v_nums V_2_NUM_TABLE := V_2_NUM_TABLE(); BEGIN v_nums.EXTEND; v_nums(1) := v_num_table(); v_nums(1).EXTEND; v_nums(1)(1) := 1; v_nums(1)(1) := v_nums(1)(1) +1; dbms_output.put_line(v_nums(1)(1) ); END;
Variable "enclose" is an archival collection, so access you an individual field of an element of the given collection by specifying the domain name, not its position:
DECLARE SUBTYPE t_rec IS TEST_TABLE%ROWTYPE; TYPE records_table IS TABLE OF t_rec; elist RECORDS_TABLE; CURSOR table_cursor IS SELECT * FROM TEST_TABLE WHERE rownum <= 20; BEGIN OPEN table_cursor; FETCH table_cursor BULK COLLECT INTO elist; FOR j IN 1..elist.COUNT LOOP elist(j).value1 := elist(j).value1 + 1; END LOOP; CLOSE table_cursor; END;
Your second example is different because you are dealing with a collection of collections.
-
Dear members,
I have a table with a few missing numbers in a col1.
How can I add rows with missing data.
beginning and ending number are given in the procedure.
We say from 1 to 10.
Table
ID col1
1 2
3 R
3 4
4 9
Required result after execution of the procedure.
Table
ID col1
1 2
3 R
3 4
4 9
9 ½
6 5
6 of 7
8 7
9 8
10 10
can I have this procedure.
concerning
teefu.
Published by: user_teefu on August 23, 2010 14:19Check this procedure...
create or replace procedure p1 (p_st number, p_end number) is cursor c1 is select col1 from tabname; k number; begin for i in p_st..p_end loop for j in c1 loop if j.col1 = i then k := 1; exit; else k := 0; end if; end loop; if k=0 then insert into tabname(col1) values (i); end if; end loop; end; SQL> select * from tabname; COL1 ---------- 1 4 5 SQL> exec p1(1,10); PL/SQL procedure successfully completed. SQL> select * from tabname; COL1 ---------- 1 4 5 2 3 6 7 8 9 10 10 rows selected.
-
How to assign a value of the element from page to main page in the column element when Cre
I have a form build on table T1. The T1 has a primary key defined (T1PK) and four other columns (C1 - C4). I have a form in this table. This form accepts the values of C1 to C4 and displayis an extra point, is not based on columns of T1 - P1_DUMMY. The form for T1PK element has the value "hidden and protected.
When creating the form, I wanted that the value of the primary key (T1PK) will be obtained through existing trigger. I want to use the value stored in the page called "P1_DUMMY" for P1_T1PK.
No matter what I do, I always get this error when I hit the button 'CREATE' on the page of the form:
ORA-01400: cannot insert NULL into ('DEV'. "" T1 ". ("' T1PK")
The Create button is a condition not to show if the the P1_T1PK page element is NULL. I created page rendering process, the process of transformation of page like this bock of PL/SQL:
: P1_T1PK: =: P1_DUMMY
But I still get ORA-01400. The form has the P1_DUMMY as display only, not not to store the State, so I can see that the P1_DUMMY element has the value I want (2).
How to assign the value stored in P1_DUMMY in P1_T1PK when I click on the button CREATE on this form?
Thank you for your time.
DanielHello
The belief question is the way in which the calculation is being defined. You are not using the &. rating (dot ampersand) in PL/SQL and SQL.Try this.
1 define the calculation on P1_T1PK of Type calculation of value of the element
2. on the next page to load textarea, enter P1_DUMMY. No. colon or &
3. give appropriate conditionsKind regards
-
PL/SQL: ORA-00947: not enough values error message
Hi all I get Error (25.63): PL/SQL: ORA-00947: not enough error message values when executing after the insert statement. I am new to Oracle SPs, if someone could help me solve the problem.
Insert in estimate (ID, mValue) values ('select (where pm.ID is null then 10))
of other pm.ID
End ID), m1.mID, (case when mValue < 1 and m1.mID in (1.7))
then mValue * 100
of another mValue
mValue end) of
Scott. Left outer join METRICS m1
Scott. (PROJECTMETRIC h m1.mID = pm.ID and pm.ID = 10)');The syntax to insert rows into a table of a subquery is as follows:
insert into table (col1, col2, ...) select ... , ..., .... from ..., .... where .... /
-
SQL Insert statement with a text and a variable
I hope it's a quick simple question. I have an anonymous PL/SQL block and you want to do an insert query that allows me to assign a variable and a text to a column. Let me give you an example:
declare
number of l_id;
l_entered varchar2 (1);
Start
Start
Select the ID
in l_id
from TABLE1;
l_entered: = 'Y ';
end;
If l_entered = "Y" then
Insert into TABLE2
(RESULT)
values
(l_id "is the new ID");
end if;
end;
However, this does not work, it won't let me enter the l_id variable, or a text value "is the new ID" but not both. Is it possible to do both?
Thank you
~ ChrisUsing of "|" between the variable and text.
something like this:(l_id * | * "is the new ID");
-
How to insert rows in Board signout to recurring weekly entires
I need help for create a simple procedure for lines inserted in the Council Signout database for entries "recurring weekly.
The schema is SIGNOUT in the DEV10G database.
There are three main tables: UKIMR, the REASONand SIGNOUT
My first thought is that the procedure takes as arguments:
-name, surname
-first name
-start date
-number of weeks
-the type of entry (for example, "telecommuting")
-Comment
Note: I use the name as args because that's how columns are configured in the UKIMR table.
So all it would do is create entries on the same day-of-the-week as the * 'start date' * for as many weeks as you indicate in the * 'number of weeks' * argument.
So this would be an example of calling script:_
* exec STP_InsertWeekly ("Lastname", "firstname", October 3, 2008 ', 5, 'Teleworking', null);
Which would insert 5 rows SIGNOUT for 5 Friday October.
Published by: user4653174 on October 3, 2008 10:28
Published by: user4653174 on October 3, 2008 10:29
Published by: user4653174 on October 3, 2008 10:31user4653174 wrote:
I want to see my procedure to insert rows in the table SIGNOUT. When I run that it is has the below error. The purpose of this procedure is for the employee to enter their name, the date they want to be turned off or work from home, or anything else, until they start, number of weeks (which will determine the number of rows will be inserted each week is a line), and comments that's what they do.Interaction with the customer as request for input values, is done in a client tool such as SQL * Plus or web applications. Not in PL/SQL. This just PL/SQL procedure accepts input parameters and can be called from a client application.
The no data found error is due to a select... IN the statement, which fails to extract a single line. You must decide what you want your procedure to be done in this case. Ignore, not, one other message ease of use or...?
And please paste formatted code using code tags. You have been told several times now, please the Act itself.
Kind regards
Rob. -
ORA-06550 assign the value to the parameter
Hi trying to assign the date quarter to a variable and get this error message, how can I assign a value to this parameter to PL/SQL:
declare
Neighborhood varchar (2);
Start
Select to_char (sysdate, 'YYYY-Q') in double shifts;
dbms_output.put_line (Quarter);
end;
[Error] Execution (05:42): ORA-06550: line 2, column 42:
PLS-00201: identifier 'vQUARTER' must be declared.
ORA-06550: line 2, column 50:
PL/SQL: ORA-00904: invalid identifier
ORA-06550: line 2, column 3:
PL/SQL: SQL statement ignored
ORA-06550: line 3, column 26:
PLS-00201: identifier 'vQUARTER' must be declared.
ORA-06550: line 3, column 5:
PL/SQL: Statement ignored
your error message refers to vQUARTER, which is not listed in your code example.
In addition, quarter is 2 characters such as defined in your code, but you ask to 6 characters in there, for example, 2016-1
Maybe you are looking for
-
How to see if there are Java in my Mac?
Hello! I saw this article. https://www.Intego.com/Mac-Security-blog/adwind-rat-malware-everything-you-need-de know. Basically, as long as I don't have Java, I have nothing to fear? I've read that recent Macs lack Java (thanks, Apple!), but is there a
-
HP officejet pro 8610: double sided printing - brochure
I'm trying to print a booklet from a pdf file. When I print double sided printing pages in reverse. Front of the faces of the page to the top and back of the page down. How can I get to printing, so that I can form a booklet?
-
Hello. I am very new to LabVIEW programming. I use the module with DAQmx 9425. It's a digital input module and I continue to read the entries (I would like to be updated only on the evolution of the entry level, but it does not support). I use the DA
-
connect the phone to external hard drive wireless
I have a laptop with Vista and a pc with Windows 7. We have an external hard drive connected to the pc. I would like to move my music files from my laptop to the external hard drive and be able to communicate with them wireless. What should I do t
-
HP Deskjet 3055 has. Unable to see the balance of the ink in the cartridges
I have HP Deskjet 3055 has (3050 all-in-One series of J611). So far, when I clicked on the HP icon on my desktop I have learned how much ink is left in my cartridges. Now I can't learn this - all I can learn from the icon is the current position of a