Inserting particular values into different rows - sql

I have a simple task to do, sadly I am stuck. I have two tables: Countries and Continents.
Countries has these columns:
CountryID, CountryName, ContinentID.
Continents has these columns :
ContinentID, ContinentName.
Now, I need to insert particular ContinentId into Countries.ContinentID i.e 1. Belgium 1.
I would like to write a INSERT INTO query, that will allow me to insert one value of ContinentID to multiple rows of CountryID. Is there a way to do that?

I think you need update statement:
update Countries set ContinentID = 1
--values (1,2,3,4,5,6) are just for example
where CountryID in (1,2,3,4,5,6)

I am not sure if I understand your question correctly
you can use SELECT in your insert statement
example:
INSERT INTO Countries (CountryID)
SELECT ContinentID FROM Continents GROUP BY ContinentName

Related

Inserting data into a table(mutliple columns) which has primary key from another data which has data except primary key

I have a table that has 3 columns ID(Primary Key), Name, City.
I need to import data from another table that has only Name and City.
I can write insert into table 1(Name, City) select Name, City from table2.
But then I need ID in table 1 which needs to be inserted using a sequence.
I tried this:
insert into table1(ID, Name,City) values(seq.nextval, select distinct name, city from table2). But I am receiving an error saying an insufficient number of values.
I am trying it in SQL Oracle. Can someone please help me with this?
You are mixing the insert ... values and insert ... select syntax.
You edited your question to include distinct, implying you have duplicate name/city pairs that you want to suppress; but neither version gets the error you reported. If you don't have duplicates then you can just do:
insert into table1(ID, Name,City)
select seq.nextval, name, city from table2;
If you do have duplicates then you can't just add the distinct keyword, but you can use a subquery:
insert into table1 (id, name, city)
select seq.nextval, name, city
from (
select distinct name, city
from table2
);
db<>fiddle
You could also set the ID via a trigger. If you we're on a recent version you could use an identity column instead - but you tagged the question with Oracle 11g, where those are not available.

SQL Function Get Column By Reference

Let's say there are 3 tables: Genders, Countries and Users. Users has among others a column named Gender and also a column named Country.
I want to add a new entry to Users and select one of the columns Male/Female {M, F} and a country from the rows of Countries dynamically just for testing purposes.
insert into dbo.[Users] (Gender, UserName, Country)
select Genders.Male, 'newbie', Countries.(the one which matches column CountryId) FROM Genders, Countries
I want to achieve this: 'M', 'newbie', MyCountry
After applying the suggestion from 'zip' I get the result 2 rows affected, same number as the external tables I'm referencing. The Query added 2 rows, so I guess I am missing the WHERE conditions.
The Genders Table is meant as a Property and will have only one row that I manually added.
Table Genders; 1 row
Male : uniqueidentifier
Female : uniqueidentifier
Countries is a table with many rows, so I want to select one matching the criteria of one of it's column values, say the value of column CountryId.
You can get a random value using:
insert into dbo.[Users] (Gender, UserName)
select top (1) g.Male, 'newbie'
from Genders.Male
order by newid();
I figuored the solution out. Thank you all who responded for pointing me in the right direction.
INSERT INTO dbo.[Users] (Gender, UserName, Country)
SELECT Genders.Male, 'newbie', Countries.CountryId
FROM Genders, Countries
WHERE Countries.ISO2 = '##'
'##' = 2 letter ISO of country.
Explanation:
1. INSERT INTO dbo.[Users] = Add a new row to Table "Users"
2. (Gender, UserName, Country) = Includes the columns in table "Users". If a column is not specified and it had a property of not allowing Nulls, an exception would be thrown!
3. FROM Genders, Countries = Include the external tables associated to look for
4. WHERE Countries.ISO2 = '##' = This condition allows you to precisely select which column of which row you seek. So I searched for a certain row where a column named ISO2 had a value '##' and looked then for the CountryId value in the same row (entry). There may be cases when multiple rows have identical value so you would have to further specify the conditions by using AND or OR oeprators.
When a table does not contain more than 1 row, I should not have to apply WHERE Conditions. It will select the default one existing. But because the Countries Table had multiple items (3 Rows), leaving the WHERE clause out, caused to add 3 times the same User, with each row having a distinct CountryId!

merge statement when not matched by source then insert to another table

I have created two tables customersrc and customertemp with the columns:
customertemp
ID name age addr cityid isactive
34 Gi 24 Chennai 1 1
customersrc
CustomerId CustomerName CustomerAge CustomerAddress
1 Gi 24 madurai
2 Pa 23 Tirupur
3 MI 27 Tirupur
Now I need to insert pa and mi data value to the temp table bcz it is not matched with the rows of customertemp. And the row gi data will be updated which was matched.
I used the following MERGE statement
DECLARE #cityid INT SET #cityid=1
MERGE Temp.dbo.customersrc as src_customer
USING ( SELECT CustomerName,CustomerAge,CustomerAddress FROM customertemp) as temp_customer
ON src_customer.name=temp_customer.CustomerName
AND
src_customer.cityid=#cityid
WHEN MATCHED THEN
UPDATE SET
src_customer.age=temp_customer.CustomerAge,
src_customer.addr=temp_customer.CustomerAddress,
src_customer.isactive=1
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET src_customer.isactive=0 ; -- here i need the insert statement to insert in another table
Questions:
is it possible to write insert statement inside the when not matched by source query?
if it is not possible then how to achieve this using merge?
in a simple set theory I need to put the customersrc(table_B)-customertemp (table_A). B-A value into the another or temp table.
One of the main usages of the MERGE statement is to perform so called "UPSERTS" (Update matching records, insert new records), so it is definitely possible to do what you want. Just add the following to the last part of your MERGE statement:
WHEN NOT MATCHED BY TARGET THEN
INSERT (name, age, addr, cityid, isactive)
VALUES (CustomerName, CustomerAge, CustomerAddress, #cityid, 1)
If you also need to insert data into a 3rd table, depending on whether rows are updated or inserted, you can use the OUTPUT clause of the merge statement. Check out the documentation: http://technet.microsoft.com/en-us/library/ms177564.aspx
Me: Why do you want to insert to another table?
You: To show the user who are not in the customertemp table.
So your requirement is not to insert into another table. Your requirement is to get the missing users.
You could do that with a dummy UPDATE (SET SomeCol = SomeCol) and OUTPUT. But that is a hack that I would try to avoid.
It is probably easier to do this in two statements. Here's how you'd get the missing rows:
SELECT temp_customer.*
FROM (SELECT CustomerName,CustomerAge,CustomerAddress FROM customertemp) as temp_customer
LEFT JOIN customersrc ON src_customer.name=temp_customer.CustomerName AND src_customer.cityid=#cityid
WHERE customersrc.cityid IS NULL

Oracle SQL - Insertion with subquery returning multiple rows

I've an issue with a n-n relationship while trying to insert in the "middle table".
The goal is to associate Commune and ZipCode (in France, a Commune is a city, and the city name can have multiple ZipCode because there are commune with the same name. But not in the same place)
And a ZipCode can handle multiple City, here is my n-n relationShip.
So here is the request i use :
INSERT INTO FR(IDCODEPOSTAL, IDCOM_SIM)
VALUES
('24209 CEDEX', (SELECT DISTINCT IDCOM_SIM FROM COMMUNE WHERE NCCENR='Creysse'));
But here the SELECT returns 2 rows. I've read much but I didn't find a way to deal with this.
I'm not sure what you are trying to achieve, but usually you'd use an INSERT ... SELECT (without the VALUES) to insert multiple rows with a single statement:
INSERT INTO FR
(IDCODEPOSTAL, IDCOM_SIM)
VALUES
SELECT '24209 CEDEX', IDCOM_SIM
FROM COMMUNE
WHERE NCCENR='Creysse';
If you however want to insert only a single row, you need to make sure the sub-select returns only one. This is usually done using an aggregate function such as max()
INSERT INTO FR
(
IDCODEPOSTAL,
IDCOM_SIM
)
VALUES
(
'24209 CEDEX',
(SELECT max(IDCOM_SIM) FROM COMMUNE WHERE NCCENR='Creysse')
);

Insert data from db to another db

I want to take values from my old database tables to new database tables.
Old db structure:
Table I: Country
CountryId
CountryName
New db structure
Table II: Countries
Id
Name
I used the following insert query like,
select 'insert into Countries (Id, Name) select ', countryid, countryname from Country
But I have the result like,
insert into Countries(Id,Name) select 1 India
insert into Countries(Id,Name) select 2 Any Country
like that.
but I need the result like,
insert into Countries (Id, Name) values (1, 'India')
To achieve this, what is the query? help me...
If there is a lot of data to transfer and multiple tables, I would suggest using Import/Export wizard provided by SQL Server Management Studio.
http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Edit:
However, if there is not lot of data and the two systems are not connected - and you need to generate script to transfer data, your query should look like this:
SELECT 'INSERT INTO Countries (Id, Name) VALUES (' + CAST(countryid AS VARCHAR(50)) + ', ''' + countryname + ''')' from Country
If both databases are on one server, you can just do like this:
insert into [db1name].[dbo].[Countries] (Id, Name)
select CountryId, CountryName
from [db2name].[dbo].[Countries]
where _your where clause_
Hope this helps
Use simple INSERT statement (database_name.[schema_name].table)
INSERT [NewDB].[your_schema].[Countries](Id,Name)
SELECT CountryId, CountryName
FROM [OldDB].[your_schema].[Country]
To be honest I do not really get the queries that you wrote.
Are you trying to build strings from your queries that you then pass again to your database?
You can just pass your values from one database to the other in one query:
/*
maybe you need to switch off identity on your target table
to get your original id values into the target table like this:
(without comment ofc ;))
*/
--SET IDENTITY_INSERT TargetDatabase.dbo.Countries ON
INSERT INTO TargetDatabase.dbo.Countries (Id, Name)
SELECT
CountryId, CountryName
FROM SourceDatabase.dbo.Country
--SET IDENTITY_INSERT TargetDatabase.dbo.Countries OFF
Or you can use a temporary table and switch the database connection after retrieving your original values.
USE SourceDatabase
DECLARE #TempTable TABLE (CountryId INT PRIMARY KEY, CountryName NVARCHAR(MAX))
INSERT INTO #TempTable (CountryId, CountryName)
SELECT
CountryId, CountryName
FROM Country
USE TargetDatabase
/*
maybe you need to switch off identity on your target table
to get your original id values into the target table like this:
(without comment ofc ;))
*/
--SET IDENTITY_INSERT Countries ON
INSERT INTO Countries (Id, Name)
SELECT
CountryId, CountryName
FROM #TempTable
--SET IDENTITY_INSERT Countries OFF
EDIT: as a previous poster mentioned, for this to work you need both databases on the same server, since you did not say anything about that i just assumed that that was the case? :D