Copy an existing row "n" number of times in SQL Server - sql

If I have a table with a row, can I insert into the same table "x" number of times making a copy of everything in the row except a few columns. Something along the lines:
INSERT INTO #tbl
(City, Region, Country)
SELECT
"Different city", Same region, Same country 5 times.
I am trying to do this without using a loop.

If you have the cities in a separate table, you should be able to do the following:
DECLARE #tbl TABLE (City varchar(20), Region varchar(20), Country varchar(20))
INSERT INTO #tbl
VALUES('Malmo', 'Skane', 'Sweden')
--Borrowing some code from #aF.
DECLARE #cities TABLE (city varchar(20))
INSERT INTO #cities values ('London')
INSERT INTO #cities values ('Lisbon')
INSERT INTO #cities values ('Paris')
INSERT INTO #cities values ('New York')
INSERT INTO #cities values ('Barcelona')
INSERT INTO #tbl
SELECT cities.city, tbl.Region, tbl.Country
FROM (select top 1 Region, Country from #tbl) tbl, #cities cities

If you have the cities in another table you can do it like this:
create table #cities (
city varchar(30)
)
INSERT INTO #cities values ('London')
INSERT INTO #cities values ('Lisbon')
INSERT INTO #cities values ('Paris')
INSERT INTO #cities values ('New York')
INSERT INTO #cities values ('Barcelona')
INSERT INTO #tbl
(City, Region, Country)
SELECT c.city, 'REGION', 'COUNTRY' from #cities c
drop table #cities

Related

How do I copy a column from one table to another table in sql

two tables
region(region_id,region_name)
countries(country_id,country_name,region_id)
there are many country_id and country_name in countries table with region_id given multiple times to those countries ( region_id are only 4)
I need to create a table or view where it shows region_name and number of countries with the regions.
CREATE TABLE regions
(
region_id NUMBER GENERATED BY DEFAULT AS IDENTITY
START WITH 5 PRIMARY KEY,
region_name VARCHAR2( 50 ) NOT NULL
);
-- countries table
CREATE TABLE countries
(
country_id CHAR( 2 ) PRIMARY KEY ,
country_name VARCHAR2( 40 ) NOT NULL,
region_id NUMBER , -- fk
CONSTRAINT fk_countries_regions FOREIGN KEY( region_id )
REFERENCES regions( region_id )
ON DELETE CASCADE
);
REM INSERTING into REGIONS
SET DEFINE OFF;
Insert into REGIONS (REGION_ID,REGION_NAME) values (1,'Europe');
Insert into REGIONS (REGION_ID,REGION_NAME) values (2,'Americas');
Insert into REGIONS (REGION_ID,REGION_NAME) values (3,'Asia');
Insert into REGIONS (REGION_ID,REGION_NAME) values (4,'Middle East and Africa');
REM INSERTING into COUNTRIES
SET DEFINE OFF;
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('AR','Argentina',2);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('AU','Australia',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('BE','Belgium',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('BR','Brazil',2);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('CA','Canada',2);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('CH','Switzerland',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('CN','China',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('DE','Germany',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('DK','Denmark',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('EG','Egypt',4);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('FR','France',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('IL','Israel',4);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('IN','India',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('IT','Italy',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('JP','Japan',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('KW','Kuwait',4);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('ML','Malaysia',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('MX','Mexico',2);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('NG','Nigeria',4);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('NL','Netherlands',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('SG','Singapore',3);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('UK','United Kingdom',1);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('US','United States of America',2);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('ZM','Zambia',4);
Insert into COUNTRIES (COUNTRY_ID,COUNTRY_NAME,REGION_ID) values ('ZW','Zimbabwe',4);
expected output = view( region_name, no. of countries)
------------------------------------------------------------------------
CREATE VIEW Region_Countries
AS
SELECT R.REGION_NAME,COUNT(COUNTRY_NAME) AS TOTAL_COUNTRIES
FROM REGIONS R
INNER JOIN COUNTRIES C ON R.REGION_ID=C.REGION_ID
GROUP BY R.REGION_NAME
GO
SELECT * FROM Region_Countries
Creating View should be a better option Rather than a table for this Requirement.
Maybe this one will work if I understood you correctly:
SELECT
REGIONS.REGION_ID,
REGIONS.REGION_NAME,
COUNT(DISTINCT COUNTRIES.COUNTRY_ID) AS num_countries
FROM COUNTRIES
JOIN REGIONS
ON
REGIONS.REGION_ID=COUNTRIES.REGION_ID
GROUP BY
REGIONS.REGION_ID,
REGIONS.REGION_NAME
And to create a view:
CREATE VIEW my_schema.name_of_my_view AS (
SELECT
REGIONS.REGION_ID,
REGIONS.REGION_NAME,
COUNT(DISTINCT COUNTRIES.COUNTRY_ID) AS num_countries
FROM COUNTRIES
JOIN REGIONS
ON
REGIONS.REGION_ID=COUNTRIES.REGION_ID
GROUP BY
REGIONS.REGION_ID,
REGIONS.REGION_NAME
);

SQL query returning values not existing in table from set in (brackets)

Need to get values which are not in table, enumerated right in TSQL query
Table Cities
create table Cities (Id int, City nvarchar (max))
insert into Cities values
(1, 'New York'),
(2, 'Moscow'),
(3, 'Mexico'),
(4, 'Kuala-Lampur')
Now I need to extract cities that exist in set
('Los Angeles', 'Moscow', 'Oslo') but not exist in Cities table.
So I need result:
Los Angeles
Olso
I know the easiest way is to use temp table like
declare #temp table (City nvarchar (max))
insert into #temp values
(Los Angeles),
(Moscow),
(Oslo)
Select City from #temp
where City not in (Select City from Cities)
But may be there is a way to avoid temp table?
You can use a derived table filled with VALUES.
SELECT *
FROM (VALUES ('Los Angeles'),
('Moscow'),
('Oslo')) given_cities (city)
WHERE given_cities.city NOT IN (SELECT cities.city
FROM cities);

I need to migrate data from one old table to a new table by storing appropriate CityId instead CityName

I'm migrating data from one table to another table in SQL Server, In this process what I need to do is "I have 10 columns in old table one column is 'CityName' which is varchar and in the new table, I have a column 'CityId' which is an integer. And I have other table which has data about city id and names. I need store the appropriate cityId in new table instead of CityName. Please help me. Thanks in advance.
You'll need to join the source table to the CityName field in the city information table:
INSERT INTO dbo.Destination (CityID, OtherStuff)
SELECT t1.CityID, t2.OtherStuff
FROM CityInformationTable t1
INNER JOIN SourceTable t2
ON t1.CityName = t2.CityName
Below should give you an idea, you need to inner join to your look up table to achieve this.
declare #t_cities table (Id int, City nvarchar(20))
insert into #t_cities
(Id, City)
values
(1, 'London'),
(2, 'Dublin'),
(3, 'Paris'),
(4, 'Berlin')
declare #t table (City nvarchar(20), SomeColumn nvarchar(10))
insert into #t
values
('London', 'AaaLon'),
('Paris', 'BeePar'),
('Berlin', 'CeeBer'),
('London', 'DeeLon'),
('Dublin', 'EeeDub')
declare #finalTable table (Id int, SomeColumn nvarchar(10))
insert into #finalTable
select c.Id, t.SomeColumn
from #t t
join #t_cities c on c.City = t.City
select * from #finalTable
Output:
Id SomeColumn
1 AaaLon
3 BeePar
4 CeeBer
1 DeeLon
2 EeeDub

Insert a row if it doesn't exist via query

I am trying to write a query that will insert a group of people into a table if that person does not exist. For example, I have table full of people and I need to add more people into the database and I don't know if they are already there. I do know that the social security number (ssn) will never be the same for two people. Could a query be used to check if the ssn is in the table and if not insert the person into the table? If the ssn is in the table then go to the next person and check?
I was thinking about using a stored procedure, but I do not have any rights to create a store procedure.
You can insert your data into a table variable or temp table and then INSERT INTO table from temp table where it does not exists in your table.
DECLARE #Inserted AS TABLE
(
NAME VARCHAR(50)
,SSN DECIMAL(10, 0)
)
INSERT INTO #Inserted
( NAME, SSN )
VALUES ( 'Bob', 123456789 )
, ( 'John', 123546789 )
, ( 'James', 123456798 )
INSERT INTO MyTable
SELECT *
FROM #Inserted AS i
LEFT OUTER JOIN MyTable AS m
ON i.SSN = m.SSN
WHERE m.SSN IS NULL
Here are a couple ideas to get you started. I use MERGE a lot because it offers so much control. You could also look into the IN clause as part of a WHERE predicate in the INSERT SELECT statement.
MERGE
DECLARE #PERSONTABLE TABLE (ID INT PRIMARY KEY IDENTITY(1,1), FirstName VARCHAR(max))
INSERT INTO #PERSONTABLE (FirstName) VALUES ('Bill'),('Sally'),('Bob')
DECLARE #NEWPEOPLE TABLE (FirstName VARCHAR(max))
INSERT INTO #NEWPEOPLE (FirstName) VALUES ('Jim'), ('Sally')
--MERGE
MERGE INTO #PERSONTABLE AS T
USING #NEWPEOPLE AS S
ON (T.FirstName = S.FirstName)
WHEN NOT MATCHED BY TARGET THEN
INSERT (FirstName) VALUES (S.FirstName);
SELECT * FROM #PERSONTABLE
EXCEPT
DECLARE #PERSONTABLE TABLE (ID INT PRIMARY KEY IDENTITY(1,1), FirstName VARCHAR(max))
INSERT INTO #PERSONTABLE (FirstName) VALUES ('Bill'),('Sally'),('Bob')
DECLARE #NEWPEOPLE TABLE (FirstName VARCHAR(max))
INSERT INTO #NEWPEOPLE (FirstName) VALUES ('Jim'), ('Sally')
--EXCEPT
INSERT INTO #PERSONTABLE (FirstName)
SELECT FirstName FROM #NEWPEOPLE
EXCEPT
SELECT FirstName FROM #PERSONTABLE
SELECT * FROM #PERSONTABLE
You could do it like this if the new people are in another table. If not, then use Vladimir's solution.
INSERT INTO People(ssn, firstname, lastname)
SELECT ssn, firstname, lastname
FROM newpeople
WHERE ssn not in (select ssn from people )
INSERT INTO People(ssn, firstname, lastname)
SELECT np.ssn, np.firstname, np.lastname
FROM newpeople np
LEFT JOIN People p on np.ssn = p.ssn
WHERE p.ssn IS NULL
Here's another option I use a lot. Normally joins are better than sub-selects... if the joined table value is null you know you don't have a hit in the joined table.

How to update column coming from TOP 1 of another table

I have 2 tables:
City table - columns CityID, Name, Period
Assets table - columns AssetID, Name
I have to update the Period column of the City table with AssetID of the Assets table matching with the top 1 where City.Name=Assets.Name. The Assets table have identical names for different assets.
Example Assets table:
AssetID Name
1 Asset1
2 Asset1
3 Asset2
4 Asset2
How can I do this? I tried with different queries but I am not able to get it.
UPDATE City
SET Period = a.AssetID
FROM (SELECT TOP 1 AssetID, Name FROM Assets ORDER BY AssetID ASC) AS a
WHERE City.Name = a.Name;
This should work:
update City
set Period = (
select top 1 a.AssetID
from Assets a
where City.Name = a.Name
order by a.AssetId asc)
Sample code to test:
create table #City (CityId varchar(20), [Name] varchar(20), Period varchar(20))
create table #Assets (AssetId varchar(20), [Name] varchar(20))
insert into #City values (1, 'Asset1', null)
insert into #City values (2, 'Asset2', null)
insert into #City values (3, 'Asset3', null)
insert into #Assets values (1, 'Asset1')
insert into #Assets values (2, 'Asset1')
insert into #Assets values (3, 'Asset1')
insert into #Assets values (4, 'Asset2')
insert into #Assets values (5, 'Asset2')
insert into #Assets values (6, 'Asset3')
insert into #Assets values (7, 'Asset3')
select * from #City
select * from #Assets
update #City
set Period = (
select top 1 a.AssetID
from #Assets a
where #City.Name = a.Name
order by a.AssetId asc)
select * from #City
drop table #City
drop table #Assets