Need SQL command that will insert a row after specific row - sql

I need SQL command that will insert a row after specific row.
Example:-
Before table
Id. Name.
1. Xyz.
2. Xyz
3. Xyz
Want result need to add 'Abc' data after each 'xyz' having same id like:-
Id. Name.
1. Xyz.
1. Abc
2. Xyz
2. Abc
3. Xyz
3. Abc

You need UNION ALL:
SELECT t.*
FROM (SELECT id, Name
FROM table t
UNION ALL
SELECT ID, 'Abc'
FROM table t
) t
ORDER BY ID, NAME;
This will not insert row, it just provide you run time view. If you want only insert then you need to truncate your table (note : take a backup of current table ) & perform insert operation.

INSERT INTO your_table
SELECT Id
,'Abc' AS Name
FROM your_table
Where Name = 'Xyz'
I am not sure if OVERRIDING SYSTEM VALUE is needed, it depends on your table. But this query should do what you need. It will get all the rows that contain the Xyz value and use the same id and a different name. Then if you order by Id because remember ordering is never guaranteed if you don't use order by

Try this
START TRANSACTION;
UPDATE table_sample SET column = column+1 WHERE column >= some_value_here ";
INSERT INTO table_sample (id, column_name) VALUES
(NULL, 'value_here');
COMMIT;

Related

Is it possible to insert multiple rows in a table based on a select returning more than one row

Using Oracle SQL, I am trying to insert into table A based on select from table B, but I am not sure how to achieve this, since the select is returning more than one row.
INSERT INTO A
VALUES
(
SELECT id FROM B WHERE status = 'APPROVED',
'Hardcoded-Value'
);
Table B:
id
status
1
APPROVED
2
DECLINED
3
APPROVED
Based on that insert, I want to achieve following:
Table A:
Column A
Column B
1
Hardcoded-Value
3
Hardcoded-Value
You can use a const in the select list
INSERT INTO A(colA, colB)
SELECT id, 'Hardcoded-Value'
FROM B
WHERE status = 'APPROVED'

Save value in local variable HANA SQL Script

I'm trying to take value from a non-empty row and overwrite it in the subsequent rows until another non-empty row appears and then write that in the subsequent rows. Coming from ABAP Background, I'm not sure how to accomplish this in HANA SQL Script. Here's a picture to show what the data looks like.
Basically 'Doe, John' should be overwritten into all the empty rows until 'Doe, Jane' appears and then 'Doe, Jane' should be overwritten into empty rows until another name appears.
My idea is to store the non-empty row in a local variable, but I haven't had much success so far. Here's my code:
tempTab1 = SELECT
CASE WHEN EMPLOYEE <> ''
THEN lv_emp = EMPLOYEE
ELSE EMPLOYEE
END AS EMPLOYEE,
FROM :tempTab;
In general, rows in dataset are unordered until you explicitly specify ORDER BY part of SQL. If you observe some order it may be a side-effect and can vary. So first of all you have to explicitly create a row number column (assume it's name is RECORD).
Then you should go this way:
Select only rows with non-empty data in column.
Use LEAD(RECORD) over(order by RECORD) to identify the next non-empty record number.
Join your source dataset to dataset defined on step 3 on between condition for RECORD field.
with a as (
select 1 as record, 'Val1' as field1 from dummy union
select 2 as record, '' as field1 from dummy union
select 3 as record, '' as field1 from dummy union
select 4 as record, 'Val2' as field1 from dummy union
select 5 as record, '' as field1 from dummy union
select 6 as record, '' from dummy union
select 7 as record, '' from dummy union
select 8 as record, 'Val3' as field1 from dummy
)
, fill_base as (
select field1, record, lead(record, 1, record) over(order by record asc) as next_record
from a
where field1 <> '' and field1 is not null
)
select
a.record
, case
when a.field1 = '' or a.field1 is null
then f.field1
else a.field1
end as field1
, a.field1 as field1_original
from a
left join fill_base as f
on a.record > f.record
and a.record < f.next_record
The performance in HANA may be bad in some cases since it process window functions very bad.
Here is another more elegant solution with two nested window functions than does not force you to write multiple selects for each column: How to make LAG() ignore NULLS in SQL Server?
You can use window aggregate function LAST_VALUE to achieve the imputation of missing values.
Sample Data
CREATE TABLE sample (id integer, sort integer, value varchar(10));
INSERT INTO sample VALUES (4711, 1, 'Hello');
INSERT INTO sample VALUES (4712, 2, null);
INSERT INTO sample VALUES (4713, 3, null);
INSERT INTO sample VALUES (4714, 4, 'World');
INSERT INTO sample VALUES (4715, 5, null);
INSERT INTO sample VALUES (4716, 6, '!');
Generate a new column with imputed values
SELECT base.*, LAST_VALUE(fill.value ORDER BY fill.sort) AS value_imputed
FROM sample base
LEFT JOIN sample fill ON fill.sort <= base.sort AND fill.value IS NOT NULL
GROUP BY base.id, base.sort, base.value
ORDER BY base.id, base.sort
Result
Note that sort could be anything determining the order (e.g. a timestamp).

SQL Get the row number of the inserted row

I am trying to get the row number of an inserted record so I can use it for a select statement. What I am trying to accomplish is insert a person into one table, get that row number and then select something from another table where the row numbers match. Here is what I got so far:
INSERT INTO TableA Values (‘Person’)
Select timeToken
From
(
Select
Row_Number() Over (Order By tokenOrder) As RowNum
, *
From TableB WHERE taken = false
) t2
Where RowNum = (Row Number of Inserted Item)
How do I get the row number of the inserted item, I want to compare ids as some records might have been deleted so they would not match.
TABLEA Data (primary key is id)
id name
3 John
12 Steve
TABLEB Data (primary key is id)
id timeToken tokenOrder taken
2 1:00am 1 false
3 2:00am 2 false
5 3:00am 3 true
6 4:00am 4 false
My expect result when I insert person, the select take would return 4:00am
I am doing this in a stored procedure.
It is an error to think that rows have numbers unless an ORDER BY clause is included.
The only way to find a row after you have inserted it is to search for it. Presumably your table has a primary key; use that to search for it.
Try This .It may help you out
Declare #TableA_PK BIGINT
INSERT INTO TableA Values ('Person')
SET #TableA_PK=SCOPE_IDENTITY()
Select timeToken
From
(
Select
Row_Number() Over (Order By tokenOrder) As RowNum
, *
From TableB WHERE taken = false
) t2
Where RowNum =#TableA_PK
SCOPE_IDENTITY(): Scope Identity will captures the last inserted record primary key value and which can be stored in a varaible and
and then it can be for further re-use
By the sounds of it you are trying to do something like what is listed on thhe following link LINK - SQL Server - Return value after INSERT
Basically :
INSERT INTO TableA (Person)
OUTPUT Inserted.ID
VALUES('bob');
Adding a foreign key constraint(referencing primary key in table A) in table b will be good since you won't be able to delete records from table A without deleting them from table B. It'll be helpful for comparing the records using ID.
Try this
declare #rowNum int;
INSERT INTO TableA Values ('Person')
SET #rowNum =SCOPE_IDENTITY()
select * from TableA where id = #rowNum

How to Iterate through table and combine it's result with the value coming from SP

I need to join two tables in following way
TABLE_A
Id Name
Table_Ref
RefID --Auto increament
I need to insert into Table_Ref and Join each inserted id with Table_A row
as
Id Name RefId
Do i need Cursors for this
or any Set based operation can let me INSERT a new row into Table_Ref and then return it like
ID NAME RefID
xxxx AAA 1
yyyy BBB 2
You can create sequences and have that value inserted into the table
create sequence SEQ_TEST
minvalue 1
maxvalue 1000000000
start with 1
increment by 1
order;
To insert into the table, use the below syntax:
Insert into table_a (id, name, refid) values ('xxxx','AAA',SEQ_TEST.nextval);
Insert into table_a (id, name, refid) values ('yyyy','BBB',SEQ_TEST.nextval);
P.S: This is the syntax in Oracle. Not sure about tsql, you might need to tweak the syntax as necessary.

Counting a cell up per Objects

i got a problem once again :D
a little info first:
im trying to copy data from one table to an other table(structure is the same).
now one cell needs to be incremented, beginns per group at 1 (just like a histroy).
i have this table:
create table My_Test/My_Test2 (
my_Id Number(8,0),
my_Num Number(6,0),
my_Data Varchar2(100));
(my_Id, my_Num is a nested PK)
if i want to insert a new row, i need to check if the value in my_id already exists.
if this is true then i need to use the next my_Num for this Id.
i have this in my Table:
My_Id My_Num My_Data
1 1 'test1'
1 2 'test2'
2 1 'test3'
if i add now a row for my_Id 1, the row would look like this:
i have this in my Table:
My_Id My_Num My_Data
1 3 'test4'
this sounds pretty easy ,now i need to make it in a SQL
and on SQL Server i had the same problem and i used this:
Insert Into My_Test (My_Id,My_Num,My_Data)
SELECT my_Id,
(
SELECT
CASE (
CASE MAX(a.my_Num)
WHEN NULL
THEN 0
Else Max(A.My_Num)
END) + b.My_Num
WHEN NULL
THEN 1
ELSE (
CASE MAX(a.My_Num)
WHEN NULL
THEN 0
Else Max(A.My_Num)
END) + b.My_Num
END
From My_Test A
where my_id = 1
)
,My_Data
From My_Test2 B
where my_id = 1;
this Select gives null back if no Rows are found in the subselect
is there a way so i could use max in the case? and if it give null back it should use 0 or 1?
Edit:
Im usung now this:
Insert INTO My_Test ( My_Id,My_Num,My_Data )
SELECT B.My_Id,
(
SELECT COALESCE(MAX(a.My_Num),0) + b.my_Num
FROM My_Test A
Where a.My_Id = b.My_Id)
,b.My_Data
FROM My_Test2 B
WHERE My_Id = 1
THX to Bharat and OMG Ponies
greets
Auro
Try this one
Insert Into My_Test (My_Id,My_Num,My_Data)
SELECT my_Id,(
SELECT MAX(NVL(My_Num,0)) + 1
From My_Test
where my_id = b.my_id
)
,My_Data
From My_Test2 B
where my_id = <your id>;
Insert Into My_Test (My_Id,My_Num,My_Data)
select My_id,coalesce(max(My_num),0),'test4' from My_Test
where My_id=1
group by My_id
All solutions have a problem in that they don't work in a multi user environment. If two sessions issue that insert statement at the same time, they would both get the same (my_id,my_num) combination, and one of them will fail with a ORA-00001 unique constraint violation. Therefore, if you need this to work in a multi user environment, the best advice is to use only one primary key column and populate it with a sequence. Keep your my_id column as well, as that is a sort-of-grouping column or foreign key column. If your end users really like to see the "my_num" column in their (web) application, you can use the row_number analytic function.
You can read more about this scenario in this blogpost of mine: http://rwijk.blogspot.com/2008/01/sequence-within-parent.html
Regards,
Rob.