How to insert more rows into a table - sql

I need to insert many rows into a table. The table has 9 columns, and for each row the values are the same, except for one column (docunumber). I could perform the same query whenever it is necessary limiting myself to change only the specified column. For example:
insert into dpa_note (testo, DATACREAZIONE, IDUTENTECREATORE, IDRUOLOCREATORE, TIPOVISIBILITA, TIPOOGGETTOASSOCIATO,
IDOGGETTOASSOCIATO,IDPEOPLEDELEGATO, IDRFASSOCIATO)
values ('Documento validato con Verapdf', 3575, 252, 'T', 'D',--here docnumber one at a time--
, NULL, NULL)
But is there a way to pass all docnumbers together and perform the insert with only one statement?

You may use an INSERT INTO ... SELECT:
INSERT INTO dpa_note (testo, DATACREAZIONE, IDUTENTECREATORE, IDRUOLOCREATORE,
TIPOVISIBILITA, TIPOOGGETTOASSOCIATO, IDOGGETTOASSOCIATO, IDPEOPLEDELEGATO,
IDRFASSOCIATO)
SELECT 'Documento validato con Verapdf', 3575, 252, 'T', 'D', TIPOOGGETTOASSOCIATO,
NULL, NULL, NULL);
It isn't clear from your question which column you want to use from the existing table. I assumed it is TIPOOGGETTOASSOCIATO.

Related

Insert new row of data in SQL table if the 2 column values do not exist

I have a PostgreSQL table interactions with columns
AAId, IDId, S, BasicInfo, DetailedInfo, BN
AAID and IDId are FK to values referencing other tables.
There are around 1540 rows in the ID table and around 12 in the AA table.
Currently in the interactions table there are only around 40 rows for the AAId value = 12 I want to insert a row for all the missing IDId values.
I have searched, but cant find an answer to inserting rows like this. I am not overly confident with SQL, I can do basics but this is a little beyond me.
To clarify, I want to perform a kind of loop where,
for each IDId from 1-1540,
if (the row with AAId = 12 and IDId(current IDId in the loop does not exist)
insert a new row with,
AAId = 12,
IDId = current IDId in the loop,
S = 1,
BasicInfo = Unlikely
DetailedInfo = Unlikely
Is there a way to do this in SQL?
Yes, this is possible. You can use data from different tables when inserting data to a table in Postgres. In your particular example, the following insert should work, as long as you have the correct primary/unique key in interactions, which is a combination of AAId and IDId:
INSERT INTO interactions (AAId, IDId, S, BasicInfo, DetailedInfo, BN)
SELECT 12, ID.ID, 1, 'Unlikely', 'Unlikely'
FROM ID
ON CONFLICT DO NOTHING;
ON CONFLICT DO NOTHING guarantees that the query will not fail when it tries to insert rows that already exist, based on the combination of AAId and IDId.
If you don't have the correct primary/unique key in interactions, you have to filter what IDs to insert manually:
INSERT INTO interactions (AAId, IDId, S, BasicInfo, DetailedInfo, BN)
SELECT 12, ID.ID, 1, 'Unlikely', 'Unlikely'
FROM ID
WHERE NOT EXISTS (
SELECT * FROM interactions AS i
WHERE i.AAId = 12 AND i.IDId = ID.ID
);

Loop through each column name from one table and insert that name into another table?

I have two tables. One table has a list of 500 columns. Another table references each column name like this
Select Top 1 * from MyReferenceTable
Which returns the results
(69, 'FirtName', 1, NULL)
(69, 'LastName', 2, NULL)
Where 'FirstName' is the name of the column from an actual table.
So I want to fill this reference table with the column names from the other table as so
Insert Into MyReferenceTable
FileId, ColumnName1, ColumnOrder, DefaultValue
Values(69, Select ColumnName From OtherTable? ,
Select Next Sequential Identity?, NULL)
My issue is how can I loop through the other table get the column name for each row, also insert an identity in sequentialOrder as ColumnOrder?
Typing out that insert statement manually for over 500 columns would take many moons.
This is a terrible idea, but the answer to your question is straight-forward:
INSERT INTO MyReferenceTabel (FileId, ColumnName1, ColumnOrder, DefaultValue)
SELECT 69, [name], [column_id], NULL
FROM sys.columns
WHERE [object_id] = OBJECT_ID('MyOtherTable')
Basically you craft a SELECT statement that returns the values you want, and then just add the INSERT statement over it.
But again, this smells of a terrible design choice that will bite you in the end. But it's still good to know how to get this information, so I'm posting this example here.

SQL, Hive select columns with same values and create new table

I have one table with two columns - Search & Affiliate but some of the values duplicated between both.
Ex: Search 123, 345, 567, 768, 008
Affiliate 425, 345, 986, 008
I want to take the ones present in both (008, 345) + all the other ones in Affiliate and create a separate table, called unique affiliate. The remaining ones in Search is also what I want to convert into another separate table called unique search.
I can create two tables separately, join common values and create a table but how do I include the rest as well with the join? Or maybe pick common values from both and create a new table but then again, what about the rest of the values in each field?
All the affiliates can be found by a simple select distinct from the Affiliate column.
The search can be found by selecting all the Search items that are NOT in the list of Search items that occur in the Affiliate column.
To get the Search items that occur in the affiliate column use an inner join sub query to select them.
Then do a SELECT on the Search column where the items are not in the list generated by the sub query
--INSERT INTO your new affiliates_table
SELECT DISTINCT Affiliate
FROM tbl_SearchAffiliate
WHERE ISNULL(Affiliate,'') <> ''
--INSERT INTO your new search_table
SELECT DISTINCT Search
FROM tbl_SearchAffiliate
WHERE Search NOT IN
( --select the search values that occur in the affilliates column
SELECT x.Search
FROM tbl_SearchAffiliate x
INNER JOIN tbl_SearchAffiliate y ON x.Search = y.Affiliate
)
AND ISNULL(Search,'') <> ''
/********************
below is the data I assumed from your question
CREATE TABLE [dbo].[tbl_SearchAffiliate](
[Search] [nvarchar](50) NULL,
[Affiliate] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'123', N'425')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'345', N'345')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'567', N'986')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'768', N'008')
GO
INSERT [dbo].[tbl_SearchAffiliate] ([Search], [Affiliate]) VALUES (N'008', NULL)
GO
*******************/

H2 SQL database - INSERT if the record does not exist

I would like initialize a H2 database, but I am not sure if the records exist. If they exist I don't want to do anything, but if they don't exist I would like to write the default values.
Something like this:
IF 'number of rows in ACCESSLEVELS' = 0
INSERT INTO ACCESSLEVELS VALUES
(0, 'admin'),
(1, 'SEO'),
(2, 'sales director'),
(3, 'manager'),
(4, 'REP')
;
MERGE INTO ACCESSLEVELS
KEY(ID)
VALUES (0, 'admin'),
(1, 'SEO'),
(2, 'sales director'),
(3, 'manager'),
(4, 'REP');
Updates existing rows, and insert rows that don't exist. If no key column is specified, the primary key columns are used to find the row.
If you do not name the columns, their values must be provided as defined in the table. If you prefer to name the columns to be more independent from their order in the table definition, or to avoid having to provide values for all columns when that is not necessary or possible:
MERGE INTO ACCESSLEVELS
(ID, LEVELNAME)
KEY(ID)
VALUES (0, 'admin'),
(1, 'SEO'),
(2, 'sales director'),
(3, 'manager'),
(4, 'REP');
Note that you must include the key column ("ID" in this example) in the column list as well as in the KEY clause.
The following works for MySQL, PostgreSQL, and the H2 database:
drop table ACCESSLEVELS;
create table ACCESSLEVELS(id int, name varchar(255));
insert into ACCESSLEVELS select * from (
select 0, 'admin' union
select 1, 'SEO' union
select 2, 'sales director' union
select 3, 'manager' union
select 4, 'REP'
) x where not exists(select * from ACCESSLEVELS);
To do this you can use MySQL Compatibility Mode in H2 database. Starting from 1.4.197 version it supports the following syntax:
INSERT IGNORE INTO table_name VALUES ...
From this pull request:
INSERT IGNORE is not supported in Regular mode, you have to enable MySQL compatibility mode explicitly by appending ;MODE=MySQL to your database URL or by executing SET MODE MySQL statement.
From official site:
INSERT IGNORE is partially supported and may be used to skip rows with duplicate keys if ON DUPLICATE KEY UPDATE is not specified.
Here is another way:
CREATE TABLE target (C1 VARCHAR(255), C2 VARCHAR(255));
MERGE INTO target AS T USING (SELECT 'foo' C1, 'bar') AS S ON T.C1=S.C1
WHEN NOT MATCHED THEN
INSERT VALUES('foo', 'bar')
When a row in S matches one or more rows in T, do nothing. But when a row in S is not matched, insert it. See "MERGE USING" for more details:
https://www.h2database.com/html/commands.html#merge_using

SQL INSERT statement for TWO TABLES at time with INNER JOIN

I have two tables hello and login_table and below is their structure
user_info
-------
some_id | name | address
login_table
-------
id | username | password
some_id and id are autoincrement indexes.
Now how can i use INSERT statement with INNER JOIN in SQL
at present, i want add below data with same some_id and id
`name` = John
`address` = wall street
`username` = john123
`password` = passw123
below code shows, what i have tried so far.
insert into login_table lt
INNER JOIN user_info ui ON ui.some_id = lt.id
(ui.name, ui.address, lt.username, lt.password)
values
('John', 'wall street', 'john123', 'passw123')
And this is not the one value, i want to add more than one value at a time.. how can i achieve.
thanks for help.
If you need to perform the two INSERT operations atomically, use a transaction:
START TRANSACTION;
INSERT INTO login_table (username, password) VALUES ('john123', 'passw123');
INSERT INTO user_info (name, address) VALUES ('John', 'wall street');
COMMIT;
N.B. Your storage engine must support transactions for this to work (e.g. InnoDB).
To insert multiple values into a table at once, use the multiple rows form of INSERT. As stated in the manual:
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
The values list for each row must be enclosed within parentheses. The following statement is illegal because the number of values in the list does not match the number of column names:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3,4,5,6,7,8,9);
VALUE is a synonym for VALUES in this context. Neither implies anything about the number of values lists, and either may be used whether there is a single values list or multiple lists.
Insert to two tables is impossible. The second part of your question is possible: you can insert multiple rows in one statement like this:
insert into some_table(col1, col2) values (1,2), (3,4), (5,6);
USE [ERPDb]
GO
INSERT INTO [AAA].[UserRole] ([UserId], [RoleId])
SELECT u.Id, (SELECT Id FROM [AAA].[Role] WHERE Title = 'Employee') FROM [AAA].[User] u
INNER JOIN [dbo].[BaseDealer] bd ON u.Id = bd.Id
WHERE bd.DealerType = 0
GO