I have a function that INSERT INTO a table some data. I do not know how much columns the table has (let it be N).
My func gets a list of N-1 params and then
INSERT INTO ... VALUES( *N-1 params* )
The last N-th column is a standart ID column, which i want to set DEFAULT (ID column has the default value = "max" and is auto incremented)
The main problem: due to the fact that i do not know names of the columns i am working with, i can't manually enter data into the database.
How to insert a row of data, if I don't know the number of columns, but I know that I have 1 less than it should be and the last column is auto incremented / has the default value?
If you know that the order of the N-1 params is exactly the same as the order of the columns in the definition of the table (the CREATE stamenet), then there is no need to enumerate the names of the columns in the INSERT statement.
Add, 1 more NULL value to the list for the ID column (at the end of the list if, as you say it is defined last):
INSERT INTO tablename VALUES(param1, param2, ..., paramN-1, NULL)
By passing NULL for the ID, it will be incremented since it is defined as AUTOINCREMENT.
See a simplified demo.
Related
I have a table Line_Production_Plan in SQL Server; it has a UID column (int, auto-increment, identity).
It also has multiple other columns. One of them is execution_priority (int, not null).
When I insert a new row into the table (via a stored procedure (without passing execution_priority or UID as parameters)), I want execution_priority to take up the same value as the corresponding UID column in during insert. Is there a way to set the default value of a column, equal to another upon insert?
The execution, priority needs to be changed from time to time. Hence I can't use identity or auto increment.
You should use IDENT_CURRENT to get the last identity value generated for the table Line_Production_Plan.
Try this code:
INSERT INTO Line_Production_Plan (execution_priority)
VALUES ((SELECT IDENT_CURRENT('Line_Production_Plan')));
I'm trying to insert a Number as an ID in a column in my database by a loop which sets the new ID by a Sequence. When I try to insert it, the row hasn't been created or the field where my number should be is null.
This only appears when I'm trying to insert the value of the current number of the sequence. Any other number can be inserted. The id isn't a primary key or foreign key, just a normal field. I have tried to insert it in a few different methods like to select it from a field or to hardcode the value in the insert script. If its hardcoded with, the value of the sid, no row is inserted.
insert into SCHULP_BEZIEHUNG (R_ID, B_ID,S_ID,WDH,HOTEL)
values(
SEQ_SCHULP_ID.NEXTVAL
,l_selected(i)
,(select distinct SSID from SCHULP_SCHULUNGEN where SID = :P2_ID and SSID is not null)
,5
,'test');
My expected result is that it inserts the nummber of SID in the column S_ID
Images of the Database:
What is this:
This only appears when I'm trying to insert the value of the current number of the sequence.
related to? If seq_schulp_id.nextval which - in your attempt - was actually seq_schulp_id.currval, then yes, it won't work until you fetch nextval first because currval isn't yet defined within the current session.
Another objection goes to :P2_ID which is an Apex page item. If you want to be able to use it, it isn't enough that you see it on the screen - it has to be put into session state. The simplest way to do that is to submit the page first, then run the process which will insert data.
On the other hand, you said that you hardcoded value (which value? :P2_ID?) but you still didn't manage to insert value into S_ID column. It means that the whole query:
select distinct SSID from SCHULP_SCHULUNGEN where SID = :P2_ID and SSID is not null
returned nothing.
You posted incomplete code (what is l_selected(i)?); I can't tell whether there's something else that might be wrong.
Guys I am trying to execute below insert statement and I keep getting the error:
cannot insert into a generated always identity column
the statement is :
INSERT INTO leaves_approval
SELECT *
FROM requests_temp r
WHERE r.civil_number = 33322
AND r.request_id = (SELECT Max(s.request_id)
FROM requests_temp s)
One of the columns in your target table (leaves_approval) contains an identity column that was defined as Generated always.
Identity columns can be created in 2 modes - Generated always, that cannot be assigned and Generated by default that can be assigned.
If you wish you can change the column mode and then do your insert "as is".
Take in consideration that this might create duplicates in the identity column or failed due to constraints.
ALTER TABLE leaves_approval MODIFY **my_identity_column** GENERATED BY DEFAULT AS IDENTITY;
Or you can exclude the identity column from the INSERT list (but you'll have to indicate the full column list, except for the identity column), e.g. -
INSERT INTO leaves_approval (c1,c2,c3,c4,...)
SELECT c1,c2,c3,c4 ...
FROM requests_temp r
WHERE r.civil_number = 33322
AND r.request_id = (SELECT Max(s.request_id)
FROM requests_temp s)
Database SQL Language Reference - CREATE TABLE
ALWAYS If you specify ALWAYS, then Oracle Database always uses the
sequence generator to assign a value to the column. If you attempt to
explicitly assign a value to the column using INSERT or UPDATE, then
an error will be returned. This is the default.
BY DEFAULT If you specify BY DEFAULT, then Oracle Database uses the
sequence generator to assign a value to the column by default, but you
can also explicitly assign a specified value to the column. If you
specify ON NULL, then Oracle Database uses the sequence generator to
assign a value to the column when a subsequent INSERT statement
attempts to assign a value that evaluates to NULL.
What don't you understand about the error? You have an "identity" column, where the value is generated as a sequence. You cannot insert into it. So, list all the other columns:
INSERT INTO LEAVES_APPROVAL(col1, col2, col3, . . .)
SELECT col1, col2, col3, . . .
FROM REQUESTS_TEMP r
WHERE r.CIVIL_NUMBER = 33322 AND
r.REQUEST_ID = (SELECT MAX(s.REQUEST_ID) FROM REQUESTS_TEMP s);
In general, it is a good idea to list all the columns in an INSERT anyway. This prevents unexpected errors, because the columns are in the wrong order or the tables have different numbers of columns.
Example: my_table_column NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY - if you have the column defined as, then it will get the value when it is NULL and will not interfere if you are to insert/update with values for that column. It worked for me.
I have one requirement. I already have a table named WorkOrder. In this table there is a column Named WorkorderId set as primary key and identity. The next one is voucherNumber. Now I want to generate voucherNumber automatically. The condition is voucher number will not repeat. E.g., first I insert 2 rows into the table and after that I delete the 2nd entry. The next time my voucher number should be 3. Again i insert 3 more entries then after that my voucher no should be 6. Then i delete one row from this table after that my voucher number should be 7. If i delete the last row (I mean 7) then next time the voucher number should the same.
Use IDENTITY(...) when creating the column. This will make a field auto-increment its value.
You'll have to drop the column first in case that it already exists. There is no (clean) way to make this happen on already existing columns.
For further information and examples you can check out http://www.w3schools.com/sql/sql_autoincrement.asp
Edit: Sorry, I have overlooked the info that you are already using IDENTITY(...) on the PK column. Unfortunately SQL-Server can only have a single column with the IDENTITY property per table... So in this case you'll have to make use of a trigger.
This is an example:
CREATE TRIGGER CountRows
ON TestCount
AFTER UPDATE
AS
UPDATE TestCount SET Cnt = Cnt +1 WHERE ID IN (SELECT ID from inserted)
GO
In case you want to enter an IDENTIFIER to the record, it is best to use uniqueIdentifier type column. It is a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.
On insertion, you can simply proceed as follows;
Insert into MyTable
(WorkorderId, WorkName) values (NewId(), 'Test')
Using this, you can be sure the Id is globally unique.
I want to make filtration on a column after selecting a specific value of another column in the same table, I tried to use #... special character followed by the column's name to get the address of this value.
My SQL statement is like the following :
SELECT ATTRIBUTE FROM TABLE WHERE FIELD = '#FIELDNAME';
If I used a specific value instead of #FIELDNAME, it will work properly but it will be static but I need it to be dynamic based on the selected value.
Create another table which will have the list of values that are in the FIELDNAME and give each record a unique id ,then retrieve the value depending on what you have selected by the name of the new table's field preceded by '#...'
I don't know if that what are you looking for, please let me know.
If no triggers are allowed, do you have any date/time column in the table? Is it possible to have that extra column anyway to see the time of a newly inserted row?
You may have to check the lastest row entered, save its field value into a variable. Then do the select based on the variable value.
Based on the vague last row id you could try the following (it's not pretty). But again, if you have date/time that's more accurate.
select attribute from table
where field = (select field from table
where rowid =(select max(rowid) from table))
;
upate
Do you have the priviledge to set up your insert command as below:
insert into table (id, col1, col2,...) values (1,'something', 'something',...)
returning id into variable; -- you may either save field or id depending on your table
Then you may use this variable to select the records you want.