Insert into SQL table with two foreign keys from Temporary table data - sql

I have a table Hub:
and second table Rates:
In this, FromHubId and ToHubId are foreign keys from Hub table
I wanna add some data from a file in Rates table. What I have tried so far is:
Create a temp Table and insert values in it:
CREATE TABLE #Table
(FromHub varchar(30),
ToHub varchar(30),
Rate float,
rate40 float,
)
INSERT INTO #Table values('AUCKLAND','AUCKLAND',229.157325588818,341.973239724851),
('AUCKLAND','BLENHEIM',1825.03244430479,2738.13624934331),
('AUCKLAND','CHRISTCHURCH',1977.80399469734,2966.11840915988),
('AUCKLAND','DUNEDIN',2280.99676393793,3422.08272879301),
('AUCKLAND','GREYMOUTH',2432.59314855822,3650.06488860958),
('BLENHEIM','AUCKLAND',1520.66450929195,2280.99676393793),
('BLENHEIM','BLENHEIM',229.157325588818,341.973239724851),
('CHRISTCHURCH','AUCKLAND',1748.64666910852,2622.97000366278),
('CHRISTCHURCH','DUNEDIN',911.92863926627,1367.89295889941),
('CHRISTCHURCH','GREYMOUTH',685.121645221953,1028.27005071905),
:
:
:;
Create another Temp Table and trying to insert values in it:
CREATE TABLE #Table1
(FromHubId uniqueidentifier,
ToHubId uniqueidentifier,
Rate float,
Rate40 float,
FromHub varchar(30),
ToHub varchar(30)
);
insert into #Table1
select h.HubId As FromHubId, h.HubId As ToHubId, t.Rate, t.Rate40, t.FromHub, t.ToHub
FROM #Table t JOIN Hub h ON
t.FromHub=h.Centre and t.ToHub=h.Centre;
select * from #Table1;
But, It only insert values where FromHub and ToHub are same. I want to insert all values i.e. for different From and To hub as well.
Any help will be appreciated. Thanks..!!

TRY THIS: you have to join separately fro both from and to hubId using table alias as below:
INSERT INTO #Table1
SELECT DISTINCT h.HubId As FromHubId,
h1.HubId As ToHubId,
t.Rate,
t.Rate40,
t.FromHub,
t.ToHub
FROM #Table t
JOIN #Hub h ON t.FromHub=h.Centre
JOIN #Hub h1 ON t.ToHub=h1.Centre;

Related

Trigger to insert same table after condition is satsified

I want to insert a row if the field 'Rem' is yes. I am using triggers. Here the issue is I want to insert the data in the same table. Could you please let me know if you have come across this scenario?
Example:
create table Table1
(
id int,
name varchar(100),
is_rem varchar(20)
);
create or replace trigger Table1Trigger
after insert
on Table1
for each row
when (new.is_rem ='yes')
begin
insert into Table1 (id, name, is_rem)
values (:new.id, :new.name, :new.is_rem);
end; /
If I am inserting the is_rem as yes, the table should have two rows of the same data.
Below should works in MySQL
create table if not exists Table1 ( id int, name varchar(100), is_rem varchar(20) );
insert into Table1
select new_id as id, new_name as name, new_is_rem as is_rem
from Table2 where new_is_rem = 'yes';

how to move record from one database to another database

I have two database,where two table are same with all schema.
I want to move specific records of employees and employeesrates with all columns of both tables.
below is the query.
CREATE TABLE #emp
(
empID INT IDENTITY(1, 1) primary key ,
Firstname varchar(20)
);
CREATE TABLE #empRates
(
ID INT IDENTITY(1, 1) primary key ,
empid int, -- foreign key from #emp
rate decimal(10,3),
startdate datetime,
enddate datetime,
);
insert into #emp (firstname) values('First')
insert into #emp (firstname) values('Second')
insert into #emp (firstname) values('Third')
insert into #empRates(empid,rate,startdate,enddate) values(1,10,'2020/01/10','2020/01/20')
insert into #empRates(empid,rate,startdate,enddate) values(1,15,'2020/01/20','2020/01/30')
insert into #empRates(empid,rate,startdate,enddate) values(2,10,'2020/01/10','2020/01/20')
insert into #empRates(empid,rate,startdate,enddate) values(3,15,'2020/01/20','2020/01/30')
select * from #emp
select * from #empRates
drop table #emp
drop table #empRates
Here both database on same server. Database1 and Database2.
below my query which tried.
insert into database2..empRates(empid,rate,startdate,enddate) select empid,rate,startdate,enddate
from database1..empRates
Here my problem is both database have different records,so identity are different,so after insert other employee rates get displayed for another like mashed up.
I am using sql server 2012.
can you please provide the way.
You should take a look at this post --> How to turn IDENTITY_INSERT on and off using SQL Server 2008?
This way you can specify value for id column during insert, so rows on destination databases will keep IDs from origin.
Hope it helps!

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

Data Definition Language (DDL) Query SQL

I'm new in query and SQL server, and I wanted to know about DDL.
I have an attribute in my Table which has more than 1 value, such as
Size = {'S', 'M', 'L'}.
How could i make the attribute in my Table with query, so i can insert multi values to one of my attribute?
You don't want to do this, because this is denormalizing your data. But, if you must.
declare #table table (id int identity(1,1), size varchar(16))
insert into #table
values
('S')
,('M')
select * from #table
update #table
set size = size + ',M'
where id = 1
select * from #table
Here is a one to many approach with a foreign key
create table #items (id int identity(1,1), descrip varchar(64))
insert into #items
values
('shirt'),
('pants')
create table #item_sizes (id int identity(1,1), size char(1), item_id int)
alter table #item_sizes
add constraint FK_item foreign key (item_id) references #items(id)
insert into #item_sizes
values
('S',1)
,('M',1)
,('L',1)
,('S',2)
select
ItemID = i.id
,i.descrip
,isiz.size
from #items i
inner join #item_sizes isiz
on isiz.item_id = i.id
drop table #items, #item_sizes
As per your requirement :
Product (...,ProductSize);
INSERT INTO Product (ProductSize) VALUES ('S')
How to query the row of ProductSize so i can insert more than one values in SQL? –
you can query like below
select * from Product where ProductSize like '%S%' or ProductSize like '%L%' or ProductSize like '%M%'

Insert data into two tables from single select statement in sql

In my Sql server there is one database Employee which has table parish. and another one database with customer which has table clients and fips.There is one stored procedure which take data from this two tables clients and fips .
now i want to revert the operation. Take data from parish table and insert into clients and fips.
Below is the stored procedure which take data from clients and fips.
ALTER PROCEDURE [dbo].[Rpt_getexportparish] #clientID AS INT,
#assessment_type AS NVARCHAR(10),
#political_subDivision AS NVARCHAR(10),
#district AS NVARCHAR(10),
#acct_status AS NVARCHAR(10),
#millage_type AS NVARCHAR(10),
#tax_year AS NVARCHAR(10)
AS
BEGIN
SELECT FIPScode AS fips_code,
f.cnty_name AS gov_name,
c.NAME AS gov_agency,
PhysicalAddress1 AS address2,
PhysicalAddress2 AS address1,
TaxYear AS tax_year,
PhysicalAddressCity AS city,
PhysicalAddressState AS state,
PhysicalAddressZip AS zip,
AssessorName AS assr_name
FROM Clients c
JOIN fips f
ON c.FIPScode = f.cnty_fips
WHERE id = #clientID
AND place_fips = #political_subDivision
END
i want reverse of above. select data from parish and insert into clients and fips table. then what is the sql query for that.
There is no relation in both table clients and fips.
The OUTPUT command will allow you to insert into a secondary Table with a single query.
Here's an example of how it works
DROP TABLE #SOURCE
DROP TABLE #TARGET1
DROP TABLE #TARGET2
CREATE TABLE #SOURCE(ID INT IDENTITY(1,1),Val FLOAT)
GO
CREATE TABLE #TARGET1(ID INT,Val FLOAT)
GO
CREATE TABLE #TARGET2(ID INT,Val FLOAT)
GO
--ADD 10 ROWS TO SOURCE TABLE
INSERT INTO #SOURCE VALUES (RAND())
GO 10
INSERT INTO #TARGET1
OUTPUT INSERTED.* INTO #TARGET2
SELECT
*
FROM
#SOURCE