How to insert results of select - sql

I am a C# dev learning SQL.
I need to publish data from one database, to another which already has the same structure and which are both on the same instance of Sql Server. By publish, I mean I want all the id's and data to be exactly the same.
The second database is an exact copy of the first.
This is the query:
Select vev.* from [dbo].[metadata_document_set] mds
inner join
[dbo].[document_metadata] dm
on mds.metadata_document_set_id = dm.metadata_document_set_id
inner join [dbo].[segment_metadata] sm
on dm.document_metadata_id = sm.document_metadata_id
inner join [dbo].[element_metadata] em
on sm.segment_metadata_id = em.segment_metadata_id
inner join [dbo].[valid_element_value] vev
on em.element_metadata_id = vev.element_metadata_id
where mds.code = 'PA'
I need to insert all the rows of valid_element_values, as well as element_metadata, segment_metadata, and document_metadata.
How do I do that?

If you are inserting to separate tables, you will have to do it one insert at a time.
insert [new_database_name].[dbo].[metadata_document_set]
Select * from [old_database_name].[dbo].[metadata_document_set]
where code = 'PA'
insert [new_database_name].[dbo].[document_metadata]
Select * from [old_database_name].[dbo].[document_metadata]
<filter as required>
and so on.
This assumes your tables are exactly the same.
NB This will not work if you have INDENTITY columns.

Select vev.* will select columns only from valid_element_value table so remove vev.* from select and mention the columns from all four table in same order as your Insert column list
Considering the target tables are created with all the required column in target database
Update : Looks like you want to insert into four different tables. Then you need four different Insert statements
INSERT INTO target_database.SCHEMA.target_valid_element_value
(vev_col1,
vev_col2,
..)
SELECT vev.col1,
vev.col2,
..
FROM [dbo].[metadata_document_set] mds
INNER JOIN [dbo].[document_metadata] dm
ON mds.metadata_document_set_id = dm.metadata_document_set_id
INNER JOIN [dbo].[segment_metadata] sm
ON dm.document_metadata_id = sm.document_metadata_id
INNER JOIN [dbo].[element_metadata] em
ON sm.segment_metadata_id = em.segment_metadata_id
INNER JOIN [dbo].[valid_element_value] vev
ON em.element_metadata_id = vev.element_metadata_id
WHERE mds.code = 'PA'
INSERT INTO target_database.SCHEMA.target_element_metadata
(em_col1,
em_col2,
..)
SELECT em.col1,
em.col2,
..
FROM [dbo].[metadata_document_set] mds
INNER JOIN [dbo].[document_metadata] dm
ON mds.metadata_document_set_id = dm.metadata_document_set_id
INNER JOIN [dbo].[segment_metadata] sm
ON dm.document_metadata_id = sm.document_metadata_id
INNER JOIN [dbo].[element_metadata] em
ON sm.segment_metadata_id = em.segment_metadata_id
INNER JOIN [dbo].[valid_element_value] vev
ON em.element_metadata_id = vev.element_metadata_id
WHERE mds.code = 'PA'
Regarding Identity, If you have identity column in your target tables and you want insert values from source for those columns as well then
set Identity_insert target_table ON
<<Insert statement>>
set Identity_insert target_table OFF
If you dont want to explicitly insert values into identity column then dont add identity column in Insert & Select column list

Lets say you have [dbo1].[metadata_document_set1] table (and it has all the columns in select query)then
INSERT INTO [dbo1].[metadata_document_set1]
Select vev.*,em.*,sm.*,dm.*,mds.* from [dbo].[metadata_document_set] mds
inner join [dbo].[document_metadata] dm
on mds.metadata_document_set_id = dm.metadata_document_set_id
inner join [dbo].[segment_metadata] sm
on dm.document_metadata_id = sm.document_metadata_id
inner join [dbo].[element_metadata] em
on sm.segment_metadata_id = em.segment_metadata_id
inner join [dbo].[valid_element_value] vev
on em.element_metadata_id = vev.element_metadata_id
where mds.code = 'PA'

Related

string_agg is to slow with big data and i need a faster solution

I am working with contacting a string from a result and it is taking to long to execute
this is the solution I have:
declare #damagedParties table (caseid varchar(max),FirstName varchar(max),LastName varchar(max),damagedName varchar(max))
insert #damagedParties
select t.caseid,ped.FirstName as FirstName,ped.LastName,concat(ped.FirstName,' ',ped.LastName) as damagedName
from [Case] t
inner join [KCC].[dbo].[Party] p1 on p1.CaseId = t.caseid
LEFT JOIN Person ped ON ped.PersonOrBusinessId = ped.PersonOrBusinessId and p1.PartyTypeRefData = 'kpcparty$PARTY_INJUREDPARTY_F'
select string_agg(d.damagedName,', ')
from #damagedParties d
group by d.caseid
The LEFT JOIN condition in the first query joins the Person table to itself on PersonOrBusinessId. Presumably, the JOIN should be from Person table to the Party table? Something like this
insert #damagedParties
select t.caseid, ped.FirstName, ped.LastName,
concat(ped.FirstName,' ',ped.LastName) as damagedName
from [Case] t
join [KCC].[dbo].[Party] p1 on p1.CaseId = t.caseid
left join Person ped ON p1.PersonOrBusinessId = ped.PersonOrBusinessId
where p1.PartyTypeRefData = 'kpcparty$PARTY_INJUREDPARTY_F';

Passing different column values to where clause

SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid = pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890'
which gives me the following output
Now I want to use the above output values to select the rows from the table "YesNoAnswerWithObservation"
I imagine it should look something like this Select * from YesNoAnswerWithObservation Where Id in (22,27,26,...23)
Only instead of typing the values inside IN clause I want to use the values in each column resulting from above-mentioned query.
I tried the below code but it returns all the rows in the table rather than rows mentioned inside the In
SELECT pims.yesnoanswerwithobservation.observation,
graphitegtccore.yesnoquestion.description,
pims.yesnoanswerwithobservation.id ObservationId
FROM pims.yesnoanswerwithobservation
INNER JOIN graphitegtccore.yesnoquestion
ON pims.yesnoanswerwithobservation.yesnoanswerid =
graphitegtccore.yesnoquestion.id
WHERE EXISTS (SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.pelvicorgandiseaseid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.gynocologicalscanid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid =
pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890')
Any help or a nudge in the right direction would be greatly appreciated
Presumably you want the ids from the first query:
SELECT awo.observation, ynq.description, ynq.id as ObservationId
FROM pims.yesnoanswerwithobservation awo JOIN
graphitegtccore.yesnoquestion ynq
ON awo.yesnoanswerid = ynq.id
WHERE ynq.id = (SELECT mer.id
FROM pims.pimscase c JOIN
pims.digitization d
ON c.digitizationid = d.id JOIN
pims.medicalexaminerreport mer
ON d.medicalexaminerreportid = mer.id JOIN
pims.icicimedicalexaminerreport imer
ON mer.id = imer.id JOIN
pims.icicimerfemaleapplicant ifa
ON imer.id = ifa.id
WHERE c.tiannumber = 'ICICI1234567890'
) ;
Notice that table aliases make the query much easier to write and to read.

How to join a same table with two tables?

I want to create an Oracle database view :
create or replace force view view_ind_pta (indi_code, nat_indi_code, indi_unite, indi_symbole, indi_lib, indi_cible, pta_intitule, indi_resp,
indi_source_info, user_code, peri_mes_code, peri_mes_lib, pta_parent, deleted,obj_intitule,pta_action)
as
select distinct
i.indi_code,
i.nat_indi_code,
i.indi_unite,
i.indi_symbole,
to_char(i.indi_lib) as indi_lib,
i.indi_cible,
concat(concat(to_char(a.pta_ref),' - '),to_char(a.pta_intitule)) as pta_intitule,
i.indi_resp,
to_char(i.indi_source_info) as indi_source_info,
u.user_code,
i.peri_mes_code ,
pm.peri_mes_lib ,
concat(concat(to_char(p.pta_ref),' - '),to_char(p.pta_intitule)) as pta_parent,
i.deleted ,
to_char(o.obj_intitule) as obj_intitule,
concat(concat(to_char(action.pta_ref),' - '),to_char(action.pta_intitule)) as pta_action
from
indicateur i
left join acteur_saisie_indicateur ai on ai.indi_code = i.indi_code
left join acteur_verif_indicateur avi on avi.indi_code = i.indi_code
left join utilisateur u on ( ai.user_code = u.user_code and avi.user_code = u.user_code)
left join objectif o on i.obj_code = o.obj_code
left join pta a on o.pta_code = a.pta_code
left join pta action on a.pta_pta_code = action.pta_code
left join pta p on action.pta_pta_code = p.pta_code
left join periodicite_mesure pm on pm.peri_mes_code = i.peri_mes_code
where p.pta_definitif = 3;
In the view there is the table utilisateur which I want to join with the two tables acteur_saisie_indicateur and acteur_verif_indicateur. I tried the and operator , but I think it is not a good idea because the query will return rows only when there are joined rows in both tables ! Although this is not necessary : I want the query to return rows even if only one table has joined rows. So how to join these three tables ?
We can include the same table in a FROM clause more than once. All we need to do is use different aliases to distinguish the instances:
left join utilisateur uai
on ai.user_code = uai.user_code
left join utilisateur uavi
on avi.user_code = uavi.user_code
The other thing you need to do is handle table's columns in the view's projection. You want to display the utilisateur values regardless of which instance the values come from, say by using nvl() or the industry standard coalesce()
coalesce(uai.user_code, uavi.user_code) as user_code
You need to join the table twice:
left join acteur_saisie_indicateur ai on ai.indi_code = i.indi_code
left join acteur_verif_indicateur avi on avi.indi_code = i.indi_code
left join utilisateur u on ai.user_code = u.user_code
left join utilisateur u2 on avi.user_code = u2.user_code

Inner join multiple ID columns with ID in foreign table to display multiple name columns

I need to make a query that inner joins 3 different id's from one table with the id from another, to then display the name value from that table in my select query. I'll try to make it a bit more clear.
In my one table I have these 3 columns with id's:
Book_Kalender.BS_ID,
Book_Kalender.BS_ID_Prio2,
Book_Kalender.BS_ID_Prio3,
These all need to be inner joined with a column in another table, which contains the name associated with these ids:
Book_Sommerhuse.[BS_ID]
In my SELECT query I am including the name column from the foreign table. I want to instead have 3 columns, each with the associated name that corresponds to the ID.
Book_Sommerhuse.BS_Navn
So far I have tried to make multiple inner joins using the AND keyword:
INNER JOIN Book_Kalender ON Book_Sommerhuse.[BS_ID] = Book_Kalender.[BS_ID]
AND Book_Sommerhuse.[BS_ID] = Book_Kalender.[BS_ID_Prio2]
But this returns and empty view from my select query. I'm also not sure how to create new columns for each name associated with the ID.
Full query:
SELECT
Book_Kalender.BK_ID,
Book_Kalender.BK_DatoFra,
Book_Kalender.BK_DatoTil,
Book_Kalender.BK_M_Navn,
Book_Kalender.BK_M_Adr,
Book_Kalender.BK_M_PostBy,
Book_Kalender.BK_M_Afd,
Book_Kalender.BK_M_MedArbNr,
Book_Kalender.BK_M_Tlf,
Book_Kalender.BK_M_Email,
Book_Kalender.BK_Tidl_Lejet,
Book_Kalender.BK_Tidl_Lejet_Txt,
Book_Kalender.BS_ID,
Book_Kalender.BS_ID_Prio2,
Book_Kalender.BS_ID_Prio3,
A.BS_Navn as BS_Navn1,
B.BS_Navn as BS_Navn2,
c.BS_Navn as BS_Navn3,
coalesce(A.BS_Navn,B.BS_Navn,c.BS_Navn) as BS_Navn
FROM
Book_Kalender
LEFT JOIN Book_Sommerhuse A ON
Book_Kalender.BS_ID = A.BS_ID
LEFT JOIN Book_Sommerhuse B ON
Book_Kalender.BS_ID_Prio2 = B.BS_ID
LEFT JOIN Book_Sommerhuse C ON
Book_Kalender.BS_ID_Prio3 = C.BS_ID
WHERE
Book_Kalender.BK_DatoFra BETWEEN #10/15/2017# AND #12/31/2018#;
You need 3 left join :
select
Book_Kalender.*,
A.BS_Navn as BS_Navn1,
B.BS_Navn as BS_Navn2,
C.BS_Navn as BS_Navn3,
coalesce(A.BS_Navn,B.BS_Navn,c.BS_Navn) as BS_Navn -- first non null BS_Navn
from
Book_Kalender
LEFT JOIN Book_Sommerhuse A ON
Book_Kalender.BS_ID = A.BS_ID
LEFT JOIN Book_Sommerhuse B ON
Book_Kalender.BS_ID_Prio2 = B.BS_ID
LEFT JOIN Book_Sommerhuse C ON
Book_Kalender.BS_ID_Prio3 = C.BS_ID
SELECT
K.BS_ID
,S1.BS_Navn
,K.BS_ID_Prio2
,S2.BS_Navn 'Prio2_BS_Navn'
,K.BS_ID_Prio3
,S3.BS_Navn 'Prio3_BS_Navn'
FROM
Book_Kalender K
LEFT JOIN
Book_Sommerhuse S1 ON S1.BS_ID = K.BS_ID
LEFT JOIN
Book_Sommerhuse S2 ON S2.BS_ID = K.BS_ID_Prio2
LEFT JOIN
Book_Sommerhuse S3 ON S3.BS_ID = K.BS_ID_Prio3
Use could use derived table which could provide you three columns data as a single column and then you could apply the join , something like this
INNER JOIN (
SELECT BS_IDs FROM Book_Kalender CROSS APPLY(
VALUES (BS_ID), (BS_ID_Prio2), (BS_ID_Prio3)) Cols(BS_IDs)
) DerivedBook_Kalender ON Book_Sommerhuse.[BS_ID] = DerivedBook_Kalender.[BS_IDs]

Inner Join in stored procedure

I have this stored procedure:
ALTER PROCEDURE [dbo].[Get_All_Items]
AS
BEGIN
SELECT
ItemID, ItemName, CategoryID, CountryID,
ItemSize, ColorID, ProductionDate, ExpiryDate,
UnitName, FirstUnitBarcode, FirstItemQuantity,
FirstUnitDefult, FirstUnitLimit,
UnitsTbl.SecondUnit, SecondUnitBarcode, SecondItemQuantity,
SecondUnitDefult, SecondUnitLimit,
ThirdUnit, ThirdUnitBarcode, ThirdItemQuantity,
ThirdUnitDefult, ThirdUnitLimit, UnitDefult,
ItemImage, ItemStatus, ItemsMainTbl.Nots,
ItemsMainTbl.CreatedBy, ItemsMainTbl.CreatedDate,
ItemsMainTbl.ModifiedBy, ItemsMainTbl.ModifiedDate
FROM
ItemsMainTbl
INNER JOIN
UnitsTbl ON ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
INNER JOIN
UnitsTbl ON ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
END
Conditions:
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
ItemsMainTbl.ThirdUnit = UnitsTbl.UnitID
How to join all three tables on that common column?
I got only the first one
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
Thanks
If you want to join the same table multiple times, you need to specify an alias for each instance of the joined table, like this:
SELECT *
FROM ItemsMainTbl
INNER JOIN UnitsTbl u1 ON ItemsMainTbl.FirstUnit = u1.UnitID
INNER JOIN UnitsTbl u2 ON ItemsMainTbl.SecondUnit = u2.UnitID
INNER JOIN UnitsTbl u3 ON ItemsMainTbl.ThirdUnit = u3.UnitID
Then in the select statement, you can differentiate between the joined instances, like this:
SELECT u1.Barcode, -- Barcode from FirstUnit
u2.Barcode, -- Barcode from SecondUnit
u3.Barcode -- Barcode from ThirdUnit
You need to define reference for you UnitsTbl. Think of these references as new objects of same class, in terms of OOP. Also, it is a good habit to use references for whenever querying over a table.
SELECT *
FROM
ItemsMainTbl t1
INNER JOIN
UnitsTbl u1 ON t1.FirstUnit = u1.UnitID
INNER JOIN
UnitsTbl u2 ON t1.SecondUnit = u2.UnitID
INNER JOIN
UnitsTbl u3 ON t1.ThirdUnit = u3.UnitID