Insert using Insert Into and Inner Join - sql-server

I'm inserting rows of data from one table's column to another table's column. This is my work done:
Insert into [Inventory](Cost)
Select cast(a.[CCost] as numeric(18,6)) from [InventoryTemp] as a
Inner join [Inventory] as b on a.[ID] = b.[ID]
I have 10000 rows of data in my [Inventory] table (ID column is filled up) but when the above query was executed, the Cost data started from 10001 until 20000.
Inventory InventoryTemp
ID Cost ID Cost
1 1 3.12
3 3 9.90
18 18 8.80
The result I want
Inventory
ID Cost
1 3.12
3 9.90
18 8.80

If I have read your question correctly, I think you are trying to update the values of the cost column in your Inventory table, based on the values in the InventoryTemp table.
Therefore you want to perform an UPDATE command rather than an INSERT.
An example of this would be:
UPDATE
Inventory
SET
Inventory.Cost = InventoryTemp.Cost
FROM
Inventory
INNER JOIN
InventoryTemp
ON
Inventory.ID = InventoryTemp.ID
For more info please see this question: How do I UPDATE from a SELECT in SQL Server?

You need to use UPDATE instead of `INSERT'
UPDATE i
SET [Cost] = it.[Cost]
FROM [Inventory] i
INNER JOIN [InventoryTemp] it
ON i.ID = it.ID

Try use update.
UPDATE b
SET b.Cost = a.Cost
FROM
[InventoryTemp] as a
Inner join [Inventory] as b on a.[ID] = b.[ID]

Related

Answer me with the update statement

I have 101 records. and the prefix is a column.
[Insurance phone] is like 589-652-5256 and I have mistakenly done like
Substring ( EE.[Insurance Phone],4,3)
which result as -65 and I wanted it as 652 So I am writing update statement for same. I have different different phone number for 101 records.
When I do a select statement I got each row's middle 3 number right, but if I use update statement then 625 [1st record of 101 record] number gets updated to all 101 records.
Below are the select and update statements.
select
IC.COMPANY_NAME, EE.[Insurance Name],
substring (EE.[Insurance Phone], 5, 3) as phone
from
Insurance_Companies_28012020 EE
join
INS_COMPANIES IC on EE.[Insurance Name] = IC.COMPANY_NAME
where
ic.IS_ACTIVE = 1
and [Insurance Phone] is not null
update BUSINESS_PHONE_NUMBERS
set PREFIX = substring(EE.[Insurance Phone], 5, 3)
from Insurance_Companies_28012020 EE
join INS_COMPANIES IC on EE.[Insurance Name] = IC.COMPANY_NAME
where ic.IS_ACTIVE = 1 and [Insurance Phone] is not null
I guess your query should look like:
update t1
set t1.PREFIX = substring(EE.[Insurance Phone], 5, 3)
from BUSINESS_PHONE_NUMBERS t1
inner join Insurance_Companies_28012020 EE on ee.KEY_COLUMN = t1.KEY_COLUMN -- here you should link these two tables
inner join INS_COMPANIES IC on EE.[Insurance Name] = IC.COMPANY_NAME
where ic.IS_ACTIVE = 1
and [Insurance Phone] is not null
Edited:
Your update statement doesn't link tables BUSINESS_PHONE_NUMBERS and Insurance_Companies_28012020, which produces a Cartesian product in the execution plan, which leads to the strange behaviour of the end update result. You get the situation: you need to update N rows, but you have N*M rows with all possible combinations. It's hard to say which one of them will be selected to update. In your case, it is the first record from Insurance_Companies_28012020 table.
Also, in your UPDATE statement you can add the condition to WHERE clause: BUSINESS_PHONE_NUMBERS.KEY_COLUMN = EE.KEY_COLUMN. This should give the same result as in my UPDATE.
3o...,
Thanks for your answer it helped me to get to the exact destination.
As I said there is no relation between ee and t1. So I need to change your update statement as below. And it worked fine for me.
update t1
set t1.PREFIX = substring(EE.[Insurance Phone], 5, 3)
from BUSINESS_PHONE_NUMBERS t1
inner join INS_COMPANIES IC on IC.INS_COMPANY_ID = t1.OWNER_ID -- here you should link these two tables
inner join Insurance_Companies_28012020 EE on EE.[Insurance Name] = IC.COMPANY_NAME
where ic.IS_ACTIVE = 1
and [Insurance Phone] is not null

Issue in Update query

I have two tables called PassengerPaymentDetails and RoomInfo. Following is the query that I used to extract some values from existing PassengerPaymentDetails table.
SELECT
COUNT(*) AS Count, RequestReference, RoomTypeID, RoomCategory
FROM
[UL_SLHEV].[dbo].[PassengerPaymentDetails]
WHERE
Status != 0
GROUP BY
RoomTypeID, RoomCategory, RequestReference
As you can see I have RoomTypeID, RoomCategory and Count in the above mentioned table.
Following screenshot has the RoomInfo table:
I want to update the RoomInfo table data from the extracted Passengerpaymentdetails table. I can map these two tables with the RequestReference.
Need to update the count value in RoomInfo table according to the Passengerpaymentdetails table count value. Can anybody please help?
UPDATE:
Following is the code that I have tried so far. It is correctly return join table. I don't know how to set the value to the RoomInfo table with the getting table. And also here I am using left join for some purpose. I want to insert the value as well if the left table contains new row with the new roomtypeId. otherwise if the right table contains the same roomtypeID update the roomInfo with the updated value from passangerpaymentdetails table.
SELECT
t1.RequestReference as RoomInfoReq,
t1.Count as RoomInfoCount,
t1.RoomTypeID as RoomInfoID,
t1.RoomCategory as RoomInfoRoomCat,
l.RequestReference as PassangerReq,
l.Count as PassangerCount,
l.RoomTypeID as PassangerRoomTypeID,
l.RoomCategory as PassangerRoomCategory
FROM (
select
count(*) as Count,
RequestReference,
RoomTypeID,
RoomCategory
FROM
[UL_SLHEV].[dbo].[PassengerPaymentDetails]
where
Status!=0 group by RoomTypeID, RoomCategory, RequestReference)
as t1
Left JOIN RoomInfo as l on
t1.RequestReference = l.RequestReference and
t1.RoomTypeID = l.RoomTypeID and
t1.RoomCategory = l.RoomCategory and
l.Status!=0)
Something like that. It would be good if you provide DDL and DML instructions to test that, however you can see the logic how to do that:
UPDATE ri
SET [COUNT] = rd.[COUNT]
FROM RoomInfo ri
JOIN (SELECT
COUNT(*) AS [Count], RequestReference, RoomTypeID, RoomCategory
FROM
[UL_SLHEV].[dbo].[PassengerPaymentDetails]
WHERE
Status != 0
GROUP BY
RoomTypeID, RoomCategory, RequestReference) rd ON rd.RoomTypeID = ri.RoomTypeID
AND rd.RoomCategory = ri.RoomCategory
AND rd.RequestReference = ri.RequestReference

multirow SQL Update not working as expected - SELECT result different from UPDATE result

I have a multiple row update query that is not working like I expect it to. The JOIN condition is adhered to in the SELECT statement, but not in the UPDATE statement.
In other words: I changed 1 row, the SELECT query shows only 1 result (as expected). I convert the query to an UPDATE statement and run it - all rows in the table are changed to the same value - the JOIN condition is totally ignored.
I thought it was due to a table variable, so I used a temp table and get the same results. I verified my JOIN condition is comparing the same datatype (it's an INNER JOIN). I'm at a loss as to why this will not work
SELECT
(o.SubTotal - o.OrderDiscounts) AS OrderSubTotal,
t.CommRate * (o.SubTotal - o.OrderDiscounts) AS CommDue,
'MODIFIED' AS "Status"
FROM
bvc_Order o
INNER JOIN
#tbl t ON o.OrderNumber = t.OrderNumber
Converted to an UPDATE statement:
UPDATE AffiliateComm
SET [OrderSubtotal] = (o.SubTotal - o.OrderDiscounts),
[CommDue] = t.CommRate * (o.SubTotal - o.OrderDiscounts),
[Status] = 'MODIFIED'
FROM
bvc_Order o
INNER JOIN
#tbl t ON o.OrderNumber = t.OrderNumber
I've done the same query with a table variable - (select works, update always updates all rows & ignores JOIN condition) no joy.
Stranger still, if I put a WHERE clause on the end, it is IGNORED!
As in
WHERE o.OrderNumber = t.OrderNumber
I've done queries like these before and never had this problem.
The output of the SELECT query (as an example when 1 row needs changing)
OrderSubTotal CommDue Status
----------------------------------
1285.20 38.56 MODIFIED
WHEN I run the update query:
(1 row(s) affected) <-This is the temp table (or variable) having 1 row inserted as it should CORRECT
(5 row(s) affected) <- This is the INCORRECT number of rows affected by the UPDATE (should be 1)
Is there a setting in SQL Server 2012 that is wrong? If you inner join a table with 1 row, it's not possible to have MORE than 1 row as a result set, right?
I'm baffled.
Presumably, you intend something like this:
UPDATE ac
SET [OrderSubtotal] = (o.SubTotal - o.OrderDiscounts),
[CommDue] = t.CommRate*(o.SubTotal - o.OrderDiscounts),
[Status] = 'MODIFIED'
FROM AffiliateComm ac INNER JOIN
bvc_Order o
ON ac.OrderNumber = o.OrderNumber INNER JOIN
#tbl t
ON o.OrderNumber = t.OrderNumber ;
In other words, AffiliateComm needs to be joined into the other tables, somehow. Otherwise, all rows in AffiliateComm will be updated, I believe with the same value. I made up an AffiliateId for the above query.
In your update:
UPDATE AffiliateComm
SET [OrderSubtotal]=(o.SubTotal - o.OrderDiscounts), [CommDue]=t.CommRate*(o.SubTotal - o.OrderDiscounts),[Status]='MODIFIED'
FROM bvc_Order o
INNER JOIN #tbl t
ON o.OrderNumber = t.OrderNumber
You tell sql server to update a table called AffiliateComm. However, this table is not included in your join.
Not knowing the schema of this table, i can only guess at whata right, possibly something like:
UPDATE a
SET [OrderSubtotal]=(o.SubTotal - o.OrderDiscounts), [CommDue]=t.CommRate*(o.SubTotal - o.OrderDiscounts),[Status]='MODIFIED'
FROM AffiliateComm A
INNER JOIN bvc_Order o
ON o.OrderNumber = a.OrderNumber
INNER JOIN #tbl t
ON o.OrderNumber = t.OrderNumbe

When a SQL Server query returns no rows(NOT null rows) how do you include that in an aggregate function?

I'm writing a query to look for courses that do not have any of its gradable items graded.
In Blackboard when a user doesn't have a grade at all(e.g. no attempt was ever made) there simply isn't a row in the table gradebook_grade
So if a course doesn't have any grades at all the gradebook_grade table does not have any rows referencing the primary key of the Blackboard course_id
This is what I've used so far:
use bblearn
select cm.course_id
from course_main cm
join gradebook_main gbm on cm.pk1 = gbm.crsmain_pk1
join gradebook_grade gbg on gbm.pk1 = gbg.gradebook_main_pk1
where cm.pk1 = 3947
group by cm.course_id
having count(gbg.pk1) <= 0
The course in question(pk1 3947) is confirmed to not have any grades. So SQL Server says 0 rows affected, naturally.
The thing is, it doesn't select the course_id. I'm guessing having doesn't account for blank/non-existent rows. Is there a way to structure the query to get the course ID when there isn't anything returned? Am I joining on the wrong columns or using where on the wrong column? Any help is appreciated.
Use a left join
select cm.course_id
from course_main cm
left join gradebook_main gbm on cm.pk1 = gbm.crsmain_pk1
left join gradebook_grade gbg on gbm.pk1 = gbg.gradebook_main_pk1
where cm.pk1 = 3947
group by cm.course_id

LEFT JOIN gets heavy as the number of records in the second table increases

I am trying to run a SELECT query using LEFT JOIN. I get a COUNT on my second table ( the table on the right side of LEFT JOIN ). This process becomes slightly heavy as the number of records on the second table goes up. My first and second table have a one-to-many relationship. The second table's CampaignId column is a foreign key to the first table's Id. This is a simplified version of my query:
SELECT a.[Id]
,a.CampaignId
,a.[Inserted] AS 'Date'
,COUNT(b.Id) AS 'Received'
FROM [CampaignRun] AS a
LEFT JOIN [CampaignRecipient] AS b
ON a.Id = b.CampaignRunId
GROUP BY
a.[Id], a.CampaignId,a.[Inserted]
HAVING
a.CampaignId = 637
ORDER BY
a.[Inserted] DESC
The number 637 is an example for one the records only.
Is there a way to make this query run faster?
Use a sub-select to calculate Received:
SELECT a.[Id]
,a.CampaignId
,a.[Inserted] AS 'Date'
, (SELECT COUNT(*) FROM [CampaignRecipient] AS b
WHERE a.Id = b.CampaignRunId ) AS 'Received'
FROM [CampaignRun] AS a
WHERE a.CampaignId = 637
ORDER BY a.[Inserted] DESC
You have unneed HAVING clause here, which you can move to WHERE clause
SELECT a.[Id]
,a.CampaignId
,a.[Inserted] AS 'Date'
,COUNT(b.Id) AS 'Received'
FROM [CampaignRun] AS a
LEFT JOIN [CampaignRecipient] AS b
ON a.Id = b.CampaignRunId
WHERE a.CampaignId = 637
GROUP BY a.[Id], a.CampaignId,a.[Inserted]
ORDER BY a.[Inserted] DESC
Also ensure that you have index on foreign key in [CampaignRecipient] table on CampaignRunId column. It's considered a good practice.

Resources