Insert into join table values per each of main table - sql

I have a table called StoreTbl to store the Stores/Markets and this table has a Boolean field called AvailableToAllCities
and there is another Table called CityTbl
And There is a join Table between them called StoreCityJoinTbl
The manager asked me to remove the field AvailableToAllCities (or not use it anymore); So I need to insert to the join table all cities for each Store,
Can I do this without use for-loop?

Without any kind of DDL, I've had to create my own, and used very limited data. This should, however, be enough to get you there:
USE Sandbox;
GO
--Sample data set up
CREATE TABLE Store (StoreID int IDENTITY(1,1), StoreName varchar(50), AvailableToAllCities bit)
CREATE TABLE City (CityID int IDENTITY(1,1), CityName varchar(50));
CREATE TABLE CityStores (ID int IDENTITY(1,1), StoreID int, CityID int)
GO
INSERT INTO City (CityName)
VALUES ('London'),('New York'),('Syndey'),('Washington'),('Paris'),('Berlin'),('Shanghai'),('Tokyo');
INSERT INTO Store (StoreName, AvailableToAllCities)
VALUES ('sdgfkljasghdbfkl',1),
('dsfjklgh',0),
('sdlafiugasdljkbfh',1),
('asdfhjklgasdfjkl',1),
('sdjlhfbvgajldavfhkl',0);
INSERT INTO CityStores (StoreID, CityID)
VALUES (2,1),(2,3),(2,6),
(5,1),(5,2),(5,7),(5,8);
GO
--So your current data looks like this
SELECT S.StoreName, C.CityName
FROM Store S
LEFT JOIN CityStores CS ON S.StoreID = CS.StoreID
JOIN City C ON CS.CityID = C.CityID
OR S.AvailableToAllCities = 1;
GO
--And now the the solution
INSERT INTO CityStores (StoreID,CityID)
SELECT S.StoreID, C.CityID
FROM Store S
CROSS JOIN City C
WHERE S.AvailableToAllCities = 1;
GO
--Drop the old column
ALTER TABLE Store DROP COLUMN AvailableToAllCities;
GO
--And now the new query:
SELECT S.StoreName, C.CityName
FROM Store S
JOIN CityStores CS ON S.StoreID = CS.StoreID
JOIN City C ON CS.CityID = C.CityID;
GO
--Clean up
DROP TABLE Store;
DROP TABLE City;
DROP TABLE CityStores;

Related

Create column with values based on join

I have two tables 1) a customer table 2)Account table. I want to see what accounts are primary and which are secondary accounts.
In one table I have accountRowId. In the other table I have PrimaryAccountRowId and SecondaryAccountRowId and ‘AccountNumber’.
For my output I would like to have all AccountNumbers in one column with all the AccountRelationship(primary or seconday) in another column beside each AccountNumber.
In order to join table, for PrimaryAccounts I would join AccountRowId on PrimaryAccountRowId and for secondary Accounts I would just flip flop and instead of having the primaryAccountRowId it would be SecondaryAccountRowId.
My Account table:
AccountRowId = 256073
AccountRowId = 342300
Customer table:
PrimaryAccountRowId = 256073
SecondaryAccountRowId = 342300
AccountNumber = 8003564
AccountNumber = 2034666
What I want to see my table look like
AccoundNumber AccountRelationship
8003564 Primary
2034666 Secondary
Please provide some helpful logic/code of how I would achieve these results.
From the OP's comments here is the table structure.
Create table Customer
(
AccountNumber Varchar(50)
, PrimaryAccountRowId Varchar(15)
, SecondaryAccountRowId Varchar(15)
);
Create table Account
(
AccountRowId Varchar(15)
);
I am still somewhat guessing here. You need to provide table structure, sample data and desired output to make it easy for people to help you. Something along these lines.
declare #Customer table
(
AccountNumber Varchar(50)
, PrimaryAccountRowId Varchar(15)
, SecondaryAccountRowId Varchar(15)
)
insert #Customer values
('8003564', '256073', null)
, ('2034666', null, '342300')
declare #Account table
(
AccountRowid Varchar(15)
)
INSERT #Account values
('256073'), ('342300')
Now that we have some tables and data to work with this just becomes a case of conditional aggregation. This should return the data you are looking for as I understand the need.
select c.AccountNumber
, AccountRelationship = max(case when p.AccountRowId is not null then 'Primary' when c.SecondaryAccountRowId is not null then 'Secondary' end)
from #Customer c
left join #Account p on p.AccountRowid = c.PrimaryAccountRowId
left join #Account s on s.AccountRowid = c.SecondaryAccountRowId
group by c.AccountNumber
order by AccountRelationship

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

How to split data in SQL Server table row

I have table of transaction which contains a column transactionId that has values like |H000021|B1|.
I need to make a join with table Category which has a column CategoryID with values like H000021.
I cannot apply join unless data is same.
So I want to split or remove the unnecessary data contained in TransctionId so that I can join both tables.
Kindly help me with the solutions.
Create a computed column with the code only.
Initial scenario:
create table Transactions
(
transactionId varchar(12) primary key,
whatever varchar(100)
)
create table Category
(
transactionId varchar(7) primary key,
name varchar(100)
)
insert into Transactions
select'|H000021|B1|', 'Anything'
insert into Category
select 'H000021', 'A category'
Add computed column:
alter table Transactions add transactionId_code as substring(transactionid, 2, 7) persisted
Join using the new computed column:
select *
from Transactions t
inner join Category c on t.transactionId_code = c.transactionId
Get a straighforward query plan:
You should fix your data so the columns are the same. But sometimes we are stuck with other people's bad design decisions. In particular, the transaction data should contain a column for the category -- even if the category is part of the id.
In any case:
select . . .
from transaction t join
category c
on transactionid like '|' + categoryid + |%';
Or if the category id is always 7 characters:
select . . .
from transaction t join
category c
on categoryid = substring(transactionid, 2, 7)
You can do this using query :
CREATE TABLE #MyTable
(PrimaryKey int PRIMARY KEY,
KeyTransacFull varchar(50)
);
GO
CREATE TABLE #MyTransaction
(PrimaryKey int PRIMARY KEY,
KeyTransac varchar(50)
);
GO
INSERT INTO #MyTable
SELECT 1, '|H000021|B1|'
INSERT INTO #MyTable
SELECT 2, '|H000021|B1|'
INSERT INTO #MyTransaction
SELECT 1, 'H000021'
SELECT * FROM #MyTable
SELECT * FROM #MyTransaction
SELECT *
FROM #MyTable
JOIN #MyTransaction ON KeyTransacFull LIKE '|'+KeyTransac+'|%'
DROP TABLE #MyTable
DROP TABLE #MyTransaction

How can I pull data from multiple sql tables using a join statement

I'm designing a simple in-office ticket system, and would like to include a field for the party responsible for the next action. To do so right this moment I'm thinking of using tableName and tableID as specifiers for the specific responsible party (could be a technician, customer, or third party, all in different tables)
It would be fine to pull that data in and run another select call using the name of the table as a parameter, but the extra data flow slows things down significantly.
Is there a way to use a single join statement to return the details of the party with a column for the table name and one for the individual table id or is there a better way to store the data from multiple potential tables?
You can use left join to achieve your requirement :-
Set Nocount On;
Declare #OfficeTickets Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,PartyType Varchar(1)
,TechnicianId Int Null
,CustomerId Int Null
,ThirdPartyId Int Null
)
Declare #OfficeTickets1 Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,TableName Varchar(100)
,TableId Int Null
)
Declare #Technician Table
(
Id Int Identity(1,1)
,TechnicianName Varchar(100)
)
Declare #Customers Table
(
Id Int Identity(1,1)
,CustomerName Varchar(100)
)
Declare #ThirdParty Table
(
Id Int Identity(1,1)
,ThirdPartyName Varchar(100)
)
Insert Into #Technician(TechnicianName) Values
('Technician_1')
,('Technician_2')
,('Technician_3')
Insert Into #Customers(CustomerName) Values
('Customer_1')
,('Customer_2')
,('Customer_3')
Insert Into #ThirdParty(ThirdPartyName) Values
('ThirdParty_1')
,('ThirdParty_2')
,('ThirdParty_3')
,('ThirdParty_4')
Insert Into #OfficeTickets(Column1,PartyType,TechnicianId,CustomerId,ThirdPartyId) Values
('ABC','T',3,Null,Null)
,('XYZ','C',Null,2,Null)
,('PUQ','P',Null,Null,4)
Insert Into #OfficeTickets1(Column1,TableName,TableId) Values
('ABC','Technician',3)
,('XYZ','Customers',2)
,('PUQ','ThirdParty',4)
---- taken separate columns for parties
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets As ot
Left Join #Technician As t On ot.PartyType = 'T' And ot.TechnicianId = t.Id
Left Join #Customers As c On ot.PartyType = 'C' And ot.CustomerId = c.Id
Left Join #ThirdParty As tp On ot.PartyType = 'P' And ot.ThirdPartyId = tp.Id
---- by TableName and TableId
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets1 As ot
Left Join #Technician As t On ot.TableName = 'Technician' And ot.TableId = t.Id
Left Join #Customers As c On ot.TableName = 'Customers' And ot.TableId = c.Id
Left Join #ThirdParty As tp On ot.TableName = 'ThirdParty' And ot.TableId = tp.Id
output:-

SSIS populating cross reference table

Destination tables look like this:
Source table look like this:
Customer
CustomerId FirstName LastName Email Address1 Address2 City Zip
Person table in destination is a base table (which will later be inherited by new customer table). So I am trying to export a row from one table and populate 3 tables in destination.
I managed to do this in following way:
Get records from source table (Customer)
Create empty AddressId field
Populate Address table using OLE DB Command task (it calls stored procedure which returns SCOPE_IDENTITY() that's mapped to AddressId field)
Repeat step 3 for populating Person table (and retrieving PersonId
Populate cross reference table PersonAddress using PersonId and AddressId fields
Screenshot of this package is below.
Biggest issue with this approach is that OLE DB Command task is inserting row by row and it makes the whole package extremely slow. Is it possible to achieve the same thing but using fast load?
I am able to do it using OLE DB Command task which calls the stored procedure and then
I don't think you need SSIS.
You can use OUTPUT clause of INSERT which returns all identity keys to a temporary table
Lets try reproduce your scenario...
set nocount on
go
create table Customer (CustomerId int, CustomerName varchar(100) null, Address1 varchar(100) null, Address2 varchar(100) )
create table [Person] (PersonId int identity, PersonName varchar(100) null)
create table [Address] (AddressId int identity, AddressLine varchar(100) null)
create table [PersonAddress] (AddressId int, PersonId int )
go
-- create some data...
insert into Customer (CustomerId) values ( 1000000 + convert(int, RAND() * 1000000) )
go 1000
update Customer
set CustomerName = 'CustomerName ' + convert(varchar, CustomerId),
Address1 = 'Address1 ' + convert(varchar, CustomerId),
Address2 = 'Address2 ' + convert(varchar, CustomerId)
go
declare #identities_Person table ([rownumber] int identity, id int)
declare #identities_Address table ([rownumber] int identity, id int)
insert into Person (PersonName)
output inserted.PersonId into #identities_Person
select
c.CustomerName
from Customer c
order by c.CustomerId
insert into [Address] (AddressLine)
output inserted.AddressId into #identities_Address
select
c.Address1
from Customer c
order by c.CustomerId
insert into [PersonAddress] (PersonId, AddressId)
select p.id, a.id
from #identities_Address a
inner join #identities_Person p on p.rownumber = a.rownumber
select *
from PersonAddress pa
inner join [Address] a on a.AddressId = pa.AddressId
inner join [Person] p on p.PersonId = pa.PersonId