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

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.

Related

select from some table based on results from a different table

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.

Delete the values from particular columns and insert new values to that columns

I need to delete the values from Cost & Remaining column from the below table and insert new values from another table. Can anyone help please?
One possible way is you can delete the columns Cost and Remaining first then you can create it.
CREATE OR REPLACE TABLE `transactions.test_table` AS
SELECT
* EXCEPT (Cost, Remaining)
FROM
`transactions.test_table`;
The above will create the table without those 2 columns. Now you can insert the data from other table by creating the other columns.
A better way to do is as follows:
CREATE OR REPLACE TABLE `transactions.test_table` AS
SELECT
table1.Date, table1.Name, table2.Cost, table2. Remaining
FROM
`transactions.test_table` table1, `transactions.other_table` table2;

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

large insert in two tables. First table will feed second table with its generated Id

One question about how to t-sql program the following query:
Table 1
I insert 400.000 mobilephonenumbers in a table with two columns. The number to insert and identity id.
Table 2
The second table is called SendList. It is a list with 3columns, a identity id, a List id, and a phonenumberid.
Table 3
Is called ListInfo and contains PK list id. and info about the list.
My question is how should I using T-sql:
Insert large list with phonenumbers to table 1, insert the generated id from the insert of phonenum. in table1, to table 2. AND in a optimized way. It cant take long time, that is my problem.
Greatly appreciated if someone could guide me on this one.
Thanks
Sebastian
What version of SQL Server are you using? If you are using 2008 you can use the OUTPUT clause to insert multiple records and output all the identity records to a table variable. Then you can use this to insert to the child tables.
DECLARE #MyTableVar table(MyID int);
INSERT MyTabLe (field1, field2)
OUTPUT INSERTED.MyID
INTO #MyTableVar
select Field1, Field2 from MyOtherTable where field3 = 'test'
--Display the result set of the table variable.
Insert MyChildTable (myID,field1, field2)
Select MyID, test, getdate() from #MyTableVar
I've not tried this directly with a bulk insert, but you could always bulkinsert to a staging table and then use the processs, described above. Inserting groups of records is much much faster than one at a time.

"select * into table" Will it work for inserting data into existing table

I am trying to insert data from one of my existing table into another existing table.
Is it possible to insert data into any existing table using select * into query.
I think it can be done using union but in that case i need to record all data of my existing table into temporary table, then drop that table and finally than apply union to insert all records into same table
eg.
select * into #tblExisting from tblExisting
drop table tblExisting
select * into tblExisting from #tblExisting union tblActualData
Here tblExisting is the table where I actually want to store all data
tblActualData is the table from where data is to be appended to tblExisting.
Is it right method.
Do we have some other alternative ?
You should try
INSERT INTO ExistingTable (Columns,..)
SELECT Columns,...
FROM OtherTable
Have a look at INSERT
and SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
No, you cannot use SELECT INTO to insert data into an existing table.
The documentation makes this very clear:
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.
You generally want to avoid using SELECT INTO in production because it gives you very little control over how the table is created, and can lead to all sorts of nasty locking and other performance problems. You should create schemas explicitly and use INSERT - even for temporary tables.
#Ryan Chase
Can you do this by selecting all columns using *?
Yes!
INSERT INTO yourtable2
SELECT * FROM yourtable1
Update from CTE? http://www.sqlservercentral.com/Forums/Topic629743-338-1.aspx