select from some table based on results from a different table - sql

I have a small table tbl_a that is something like
id
fieldName
tableName
1
field1
tbl_1
2
field2
tbl_1
3
field3
tbl_2
and I want to be able to come up with a function or proc or something where I can specify the fieldId from tbl_a and then query the correct field and table from that. something like
select * from my_function(3)
should end up being equivalent to
select field3 from tbl_2
I've been looking into dynamic sql and user functions but can't seem to figure out how to feed the results of the query into another.
EDIT:
As #Larnu correctly surmised, there is a larger task hiding behind the one posed in the original question. The premise is this:
tblArchive stores the values of certain "static" fields (found in other tables) with a Date attached. If/when these fields are changed in their original table, then a record is inserted into tblArchive. More-or-less an audit table.
eg: in tbl_accounts, AdjustmentFactor field (fieldId=3) for accountId=1 changes from 1.0 to 0.5 on '2022-06-10'.
Insert into tblArchive (fieldId, accountId, date, value) values (3,1,'2022-06-10',0.5)
tblArchive was only created in 2019. I've been tasked with back-filling records from 2017 on. That is, to insert records that would have been inserted had tblArchive existed in 2017.
In order to backfill, I have to look into the real audit tables (for previous example this would be tblAccountsAudit for that particular fieldId).
The fields of interest and their respective tables are given in tblFields. tblFields would be tbl_a from the original question and for the example given we'd have something like
id
fieldName
tableName
3
AdjustmentFactor
tbl_accounts
Assume also that the design is what it is and I have no power to overhaul the design/structure of the database.

It sounds like you need something like this.
CREATE FUNCTION myfunction (
#key INT
)
RETURNS TABLE
AS
RETURN
SELECT
id,
fieldName,
tableName
FROM
tbl_a
WHERE
id = #key;
This will give return the table you are after through a function.

Related

Insert Column with same value

I am running a query on the table "performance" and I want to insert a column with the same value for all the rows without using alter, update etc.
I wrote a case statement and it works but is there a more refined way?
here is a short query:
SELECT id, name, class,
CASE
WHEN id IS NOT NULL THEN 'Actuals'
ELSE 'Forecast'
END AS type
FROM performance
Basically I need all the values to be labeled "Actuals".
There are many other datasets for which I will use different labels and then append all of them
Just to be clear - don't need to update the table performance itself
use common table expression for your case.
It will add new column in your existing data and you may use this for your further process.
For your point it is not adding nor inserting anything in your existing db structure.
with CTE as (
SELECT id, name, class,
CASE WHEN id IS NOT NULL THEN 'Actuals' ELSE 'Forecast' END AS type
FROM table_performance
)
select * from CTE ----- It give you all the columns from [table] and add another column as you needed.
OR
You may create a view for same, if this condition is fixed.

SQL - Create a table from itself with new rows (insert into?)

I want to create a table that will hold its currents rows and add new ones for each month but didn't find how to join the table with itself to get what I want.
Today I have a table with "current_records" from february
and a create table statement that get my values from february and do an union on another "current_month_table" to join all my records on a "all_records_table" so I get all my february+march records. But I don't want to create a new table for each month.
Tomorrow I'll want to have my "current_month_table" to list the april results and to append them to the existing "all_records_table" results.
I checked there Create SQL table with the data from another table as it seemed to provide good advice but I didnt get it to work.
CREATE TABLE `/Users/SQL essais/current_month_table` as c_m_t
INSERT INTO `/Users/SQL essais/all_records_table`
SELECT
*
FROM `/data`
the result was a full replacement of the data from current_month_table by the data from all_records_table where I wanted the data to go the other way around (and not replacing but adding rows).
Sounds like you just need an Insert-Select.
INSERT INTO all_records_table (Field1, Field2, Field3)
(SELECT Field1, Field2, Field3
FROM current_month_table)
You can add whatever joins and filters you need in the Select statement.
If you need more information, post additional examples of the data that is in the tables.

How to insert generated id into a results table

I have the following query
SELECT q.pol_id
FROM quot q
,fgn_clm_hist fch
WHERE q.quot_id = fch.quot_id
UNION
SELECT q.pol_id
FROM tdb2wccu.quot q
WHERE q.nr_prr_ls_yr_cov IS NOT NULL
For every row in that result set, I want to create a new row in another table (call it table1) and update pol_id in the quot table (from the above result set) with the generated primary key from the inserted row in table1.
table1 has two columns. id and timestamp.
I'm using db2 10.1.
I've tried numerous things and have been unsuccessful for quite a while. Thanks!
Simple solution: create a new table for the result set of your query, which has an identity column in it. Then, after running your query, update the pol_id field with the newly generated ID in your result table.
Alteratively, you can do it more manually by using the the ROW_NUMBER() OLAP function, which I often found convenient for creating IDs. For this it is convenient to use a stored procedure which does the following:
get the maximum old id from Table1 and write it into a variable old_max_id.
after generating the result set, write the row-numbers into the table1, maybe by something like
INSERT INTO TABLE1
SELECT ROW_NUMBER() OVER (PARTITION BY <primary-key> ORDER BY <whatever-you-want>)
+ OLD_MAX_ID
, CURRENT TIMESTAMP
FROM (<here comes your SQL query>)
Either write the result set into a table or return a cursor to it. Here you should either use the same ROW_NUMBER statement as above or directly use the ID from Table1.

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..

SQL insert row with one change

I have this table:
Table1:
id text
1 lala
And i want take first row and copy it, but the id 1 change to 2.
Can you help me with this problem?
A SQL table has no concept of "first" row. You can however select a row based on its characteristics. So, the following would work:
insert into Table1(id, text)
select 2, text
from Table1
where id = 1;
As another note, when creating the table, you can have the id column be auto-incremented. The syntax varies from database to database. If id were auto-incremented, then you could just do:
insert into Table1(text)
select text
from Table1
where id = 1;
And you would be confident that the new row would have a unique id.
Kate - Gordon's answer is technically correct. However, I would like to know more about why you want to do this.
If you're intent is to have the field increment with the insertion of each new row, manually setting the id column value isn't a great idea - it becomes very easy for there to be a conflict with two rows attempting to use the same id at the same time.
I would recommend using an IDENTITY field for this (MS SQL Server -- use an AUTO_INCREMENT field in MySQL). You could then do the insert as follows:
INSERT INTO Table1 (text)
SELECT text
FROM Table1
WHERE id = 1
SQL Server would automatically assign a new, unique value to the id field.