SQL Insert existing/duplicate row into table but change only one column value? - sql

I have Audit table with more than 50 columns and need to insert desired row (duplicate) by changing just one column value (column CreatedDate, set value to GETDATE()). I know this can be achieved by INSERT INTO SELECT * FROM but as there is more han 50 columns, code would seem messy:
INSERT INTO Audit_Table (Col1, Col2, .....CreatedDate, ......, Col50, ...ColN)
SELECT (Col1, Col2, .....GETDATE(), ......, Col50, ...ColN) FROM Audit_Table
WHERE Audit_Table.Id = Desired_Id
If i shouldn't change CreatedDate column value, it would be very simple:
INSERT INTO Audit_Table SELECT * FROM Audit_Table WHERE Audit_Table.ID = Desired_Id
Is there any other way to duplicate row and change only one/desired column value?

You can insert the record into a temporary table, update the CreatedDate column to GETDATE(), then insert it into the Audit_Table.

No. There is no way to say * except column_foo in SQL.
The workaround would be to generate the
SELECT
col1
, col2
, [...]
, coln
FROM foo;
statement (or parts of it) by querying the database's system catalogue for the column names in their order. There is always a table with all tables and a table with all columns.
Then, make sure you put the necessary commas in the right place (or remove them where you don't need them, or generate the comma in all rows of the report but the first - by using the ROW_NUMBER() OLAP function and evaluating whether it returns 1 or something else). Finally, edit the right date column, by replacing it with CURRENT_DATE or whatever your database uses for the current day.
Good luck -
Marco

You can build upon your existing idea. Just duplicate the row (I assume, you have an auto-incrementing primary key column) and then in a separate query update the time i.e.
Do this :
INSERT INTO Audit_Table SELECT * FROM Audit_Table WHERE Audit_Table.ID = Desired_Id
And then :
UPDATE Audit_Table SET CreatedDate = GETDATE() WHERE primaryKeyID = newPrimaryKeyID
Hope this helps!!!

try below as reference
you can use below statement to copy the all rows,
mysql> insert into newstudent select * from students;
you can use below statement to copy the specific row from table,
mysql> insert into newstudent
-> select id, name, age, address
-> from students
-> where
-> id = 1248;
you can use below statement to copy the either of the row from table,
mysql> insert into newstudent
-> select id, name, age, address
-> from students
-> where
-> id = 1248 or id=1249;
use limit clause also along with this

Related

Generate insert column based on select columns

I have a scenario, where 100's of select statements sql's are in one metadata table or some text file.
Need to insert all sql results into one specific table. (master table has col1, col2,col3 .... 200columns )
problem im facing(ORA-00947) is every select statement has different number of columns.
.. i need to generate INSERT PART.
CASE 1 : INSERT INTO (COL1,COL2,COL3) <<this select part comes from file/variable>>
CASE 2 : INSERT INTO (COL1) <<this select part comes from file/variable>>
CASE 3 : INSERT INTO (COL1) <<this select part comes from file/variable>>
have to figure out how many columns are in select part then generate INSERT part.
.
Thought of create as select but problem is some select statement has max(col) without alias so it will fail.
This is too long for a comment.
If you are storing SQL in a table, then you are constructing your query dynamically. So, update the table and list the columns that you want.
You could then construct the inserts as :
insert into master_table (<column list here>)
<select here>;
Both the select and column list would come from the table.
By far the easiest is to create a view for each SELECT statement. Then you can query the USER_TAB_COLUMNS view on the view name and get the column names.
Best regards,
Stew Ashton

JOOQ: extract value from Field

I have a table with PK and another column for other id. In some cases i need to insert record with equal values in both columns. For primary key values i'm using sequence, which gives a Field<Long> from Sequences.MY_SEQ.nextval().
How can i extract value from a Field<Long> for guaranteed insert same ids in both columns? Using Field<Long> in insert clause generates 2 different ids in columns.
Here is the solution:
Long id = dsl.select(Sequences.MY_SEQ.nextval()).fetchOne().value1();
Your own solution works, of course, but it will generate two round trips to the database. One for fetching the sequence value and another one for the insert. If that's not a problem, perfect. Otherwise, you can still do it in one single query using INSERT .. SELECT:
In SQL:
(using Oracle syntax. Your SQL syntax may vary...)
INSERT INTO my_table (col1, col2, val)
SELECT t.id, t.id, 'abc'
FROM (
SELECT my_seq.nextval AS id
FROM dual
) t
With jOOQ
Table<?> t = table(select(MY_SEQ.nextval().as("id"))).as("t");
dsl.insertInto(MY_TABLE)
.columns(MY_TABLE.COL1, MY_TABLE.COL2, MY_TABLE.VAL)
.select(
select(t.field("id"), t.field("id"), val("abc"))
.from(t))
.execute();

sql server add a row with same records except for ID

My code is as below"
select * into tbltemp
from table1 where ID='12345'
update tbltemp set ID='54321'where ID='12345'
insert into table1
select * from tbltemp where ID='54321'
drop table tbltemp
When executing insert into query, I got error saying 'Insert Error: Column name or number of supplied values does not match table definition.'
I wonder how I can deal with that?
My table1 has 50 columns with three computed columns.
Thanks for advice!
table1 and tbltemp must match by number of columns. You must explicitly name the columns do not use the * sign in insert into from select, if number of columns do not match.
I just realized that when I have computed columns, the query doesn't work well.
So I delete the computed columns before copy a new one, then do an insert into select *, then add computed columns back, in this way I can save the time for writing 50 fields.
You can't insert a computed column. You need to select especific fields in select and in value() statements. No select *

How to select data and insert those data using single sql?

I want to select some data using simple sql and insert those data into another table. Both table are same. Data types and column names all are same. Simply those are temporary table of masters table. Using single sql I want to insert those data into another table and in the where condition I check E_ID=? checking part. My another problem is sometime there may be any matching rows in the table. In that time is it may be out sql exception? Another problem is it may be multiple matching rows. That means one E_ID may have multiple rows. As a example in my attachment_master and attachments_temp table has multiple rows for one single ID. How do I solve those problems? I have another problem. My master table data can insert temp table using following code. But I want to change only one column and others are same data. Because I want to change temp table status column.
insert into dates_temp_table SELECT * FROM master_dates_table where e_id=?;
In here all data insert into my dates_temp_table. But I want to add all column data and change only dates_temp_table status column as "Modified". How should I change this code?
You could try this:
insert into table1 ( col1, col2, col3,.... )
SELECT col1, col2, col3, ....
FROM table2 where (you can check any condition here on table1 or table2 or mixed)
For more info have a look here and this similar question
Hope it may help you.
EDit : If I understand your requirement properly then this may be a helpful solution for you:
insert into table1 ( col-1, col-2, col-3,...., col-n, <Your modification col name here> )
SELECT col-1, col-2, col-3,...., col-n, 'modified'
FROM table2 where table1.e_id=<your id value here>
As per your comment in above other answer:
"I send my E_ID. I don't want to matching and get. I send my E_ID and
if that ID available I insert those data into my temp table and change
temp table status as 'Modified' and otherwise don't do anything."
As according to your above statements, If given e_id is there it will copy all the columns values to your table1 and will place a value 'modified' in the 'status' column of your table1
For more info look here
You can use merge statement if I understand your requirement correctly.
Documentation
As I do not have your table structure below is based on assumption, see whether this cater your requirement. I am assuming that e_id is primary key or change as per your table design.
MERGE INTO dates_temp_table trgt
USING (SELECT * FROM master_dates_table WHERE e_id=100) src
ON (trgt.prm_key = src.prm_key)
WHEN NOT MATCHED
THEN
INSERT (trgt.col, trgt.col2, trgt.status)
VALUES (src.col, src.col2, 'Modified');
More information and examples here
insert into tablename( column1, column2, column3,column4 ) SELECT column1,
column2, column3,column4 from anothertablename where tablename.ID=anothertablename.ID
IF multiple values are there then it will return the last result..If not you have narrow your search..

Is it possible to copy some rows from one table to the other along with rowids?

If I type:
INSERT INTO table_b
SELECT rowid, somecolumn
FROM table_a
...the rowid column would copy into new table as ordinary column and this would most likely produce an error since columns wouldn't match.
But is there a way to copy exactly the same rowids from old table to new when I'm populating it fresh ?
I know it is possible to do it that way:
INSERT INTO table_b
(rowid, othercolumn)
VALUES (334, 'sometext')
...but that needs to be write row by row instead of one line sql command.
The first SQL you write is correct and will copy all information matching the columns.
You can also use a query like this:
INSERT INTO table2( rowId, rowValue)
SELECT rowId, rowValue FROM table1
Have you tried this:
INSERT INTO table_b (target_name, target_name2)
SELECT rowid, somecolumn
FROM table_a
Should work fine. But I've not done it on sqlite...