SQL Select rows from 1st table and Update into 2nd Table - sql-server

I have two tables, tblCity and tblCountry and there's no relationship between them at the moment. I need to add CountryIds from tblCountry into tblCity.
This is tblCity:
This is tblCountry:
I need to UPDATE tblCity.CountryId (which is NULL at the moment) with corresponding tblCountry.CountryId
I have ISO2 and ISO3 country codes in both tables, so please help me with select and update queries for SQL Server.

This statement will match on both ISO2 and ISO3 columns to do the update:
UPDATE
ci
SET
ci.CountryId = co.CountryId
FROM
tblCity ci
JOIN
tblCountry co
ON
ci.ISO2 = co.CountryISO2
AND
ci.ISO3 = co.CountryISO3
WHERE
ci.CountryId IS NULL

Related

Why trigger is doing unnecessary subtraction after a query in sql?

I have two tables:
Order and
Product.
I want a specific column(OnShelfQuantity) in the Product table to be updated as a new row is added in the Order table. I have used the below query to implement a trigger which will do that. But the problem is that when I insert a row in the Order table and then later check the Product table to see the changes, I notice that the Product table has been updated 3 times. For e.g: Order quantity inserted = 10, then only 10 should be subtracted from Product_TAB.OnShelfQuantity. But 30 gets subtracted. Please help!
create trigger dbo.Trigge
ON dbo.Ordertable
AFTER INSERT
AS
BEGIN
update Product_TAB set OnShelfQuantity= Product_TAB.OnShelfQuantity - Ordertable.Quantity
FROM dbo.Product_TAB
INNER JOIN Ordertable
ON Ordertable.ProductID = Product_TAB.ProductID;
END;
I think, you can use INSERTED table to resolve this Issue.
Inserted table is a table which is used by triggers to store the frequently inserted records in the tables.
So, you can use the same in your update statement to avoid this.
update Product_TAB set OnShelfQuantity= Product_TAB.OnShelfQuantity -
Ordertable.Quantity
FROM dbo.Product_TAB
INNER JOIN Ordertable ON Ordertable.ProductID = Product_TAB.ProductID
INNER JOIN inserted INS ON INS.Order_ID=Ordertable.Order_ID
You can have multiple rows in the inserted table. And, these rows could have the same product. A row in the target table is only updated once in an update statement. Hence, you want to aggregate the data before the update:
create trigger dbo.Trigge
ON dbo.Ordertable
AFTER INSERT
AS
BEGIN
update p
set OnShelfQuantity= p.OnShelfQuantity - i.total_quantity
from dbo.Product_TAB p JOIN
(SELECT i.ProductId, SUM(i.Quantity) as total_quantity
FROM inserted i
GROUP BY i.ProductId
) i
on i.ProductID = p.ProductID;
END;
Note that this only uses inserted and not the original table.
So the issue was that I was inserting new rows but with the same Order ID. This is why it was doing additional subtraction which I didn't require. So now I have to just insert a new row but with unique OrderID. Thanks to everyone who replied above!

SQL Server Trigger not work propertly with Entity Framework and Self Tracking Entities

I have a table in SQL Server with these columns:
Name
Description
Volume
LastUpdate
For this table there is a trigger
CREATE TRIGGER [dbo].[Table1_Trigger1]
ON [dbo].[Deals]
AFTER INSERT, UPDATE
AS
BEGIN
IF(UPDATE(Volume))
BEGIN
UPDATE Table2
SET TotalVolume = Volume * 100;
END
END
The problem is that the other table records are updated even when the description column is updated (by Entity Framework) and not the volume column.
You probably need something like this in your trigger
The sample will need changes by you offcourse, I dont know your table layout and what exact you want to achieve.
update table2
set TotalValue = Volume * 100
where ID in (select i.ID from inserted i
left outer join deleted d on i.ID = d.ID
where i.Volume <> isnull(d.Volume, -1)
)
Also note that when you are inserting the deleted table will be empty.

Ms Access Query

If there are two tables. Table A has table_code as PK and its FK in Table B.
How can query be designed so that the results display all those values of table_code which is in Table A but not in Table B?
Tried all three joins
Tried Criteria is null and is not null
try
SELECT tableA.table_code
FROM tableA LEFT JOIN tableB ON tableA.table_code = tableB.table_code
WHERE (((tableB.table_code) Is Null));
if this doesn't help, show us the SQL you tried.

Where statement with conditions is multiple tables

I need my code to set values of a column based on two criteria: the value of a different column in the same table and a value of a column in a different table. Is there a way to use the where statement to look at criteria in different tables?
Below is pseudo code that doesn't work but captures what I am trying to do.
UPDATE Table1
SET CustomerStatus_2003 = 'New'
FROM Table1, Table2
WHERE Table1.Column1 = 'New'
AND Table2.Column1 = '2003'
AND Table1.Column2= Table2.Column2
Thanks for your help!
You should always alias your tables and use a JOIN when you are using more than one table in a statement. Here is some code that does what you are looking for
UPDATE t
SET myColumn = 'New'
FROM MyTable t
JOIN OtherTable t2 ON t.Column = t2.Column
WHERE t.SomeCondition
AND t2.SomeOtherCondition

Update statement to update multiple rows

I have a question regarding the following syntax. Is there a cleaner way to roll this up into one statement rather than two. I've tried several iterations but this seems to be the only way I can successfully execute these two statements.
UPDATE employee
SET hire_date = '1979-03-15'
WHERE emp_id = 'PMA42628M'
UPDATE employee
SET hire_date = '1988-12-22'
where emp_id = 'PSA89086M';
I tried this as well and I also tried using an AND statement. Neither worked. Basically I am looking for a less newbie way then the method above, if one exists. I spent a long time searching and did not find one.
UPDATE employee
SET hire_date = ('1979-03-15', '1988-12-22')
WHERE emp_id = ('PMA42628M', 'PSA89086M');
Appriciate any advice on this one, and by the way, I am using sql server.
Thanks
Try this one, this will combine multiple selects and returns them as if they come from the DB:
UPDATE e
SET hire_date = t.hire_date
FROM dbo.employee e
JOIN (
SELECT emp_id = 'PMA42628M', hire_date = '1979-03-15'
UNION ALL
SELECT emp_id = 'PSA89086M', hire_date = '1988-12-22'
) t ON t.emp_id = e.emp_id
If you are using SQL Server 2008 or later version, you could also use a different syntax for the derived table:
UPDATE e
SET hire_date = t.hire_date
FROM dbo.employee e
JOIN (
VALUES
('PMA42628M', '1979-03-15'),
('PSA89086M', '1988-12-22')
) t (emp_id, hire_date) ON t.emp_id = e.emp_id
I am looking for a less newbie way
Doing two separate update statements is (according to me) "the less newbie way" you could complicate stuff and do something like this.
update employee
set hire_date = case emp_id
when 'PMA42628M' then '1979-03-15'
when 'PSA89086M' then '1988-12-22'
end
where emp_id in ('PMA42628M', 'PSA89086M')
but what would that gain you? The entire update would run in one implicit transaction so if you want your two updates to be in a transaction you just use begin transaction .... commit.
You can make a temporary table or a table variable containing the updates you want to do, then run the UPDATE statement linking the table to the table you intend to update.
Note that for two updates, you get two statements: the INSERT into the update table and the UPDATE statement itself. The number of statements remains two though for as many updates you need to do.
CREATE TABLE #employee (emp_id VARCHAR(9) NOT NULL PRIMARY KEY,hire_date DATE NOT NULL);
INSERT INTO #employee (emp_id,hire_date)
VALUES ('PMA42628M','2013-06-05'),('PSA89086M','2013-06-05');
CREATE TABLE #target_updates(emp_id VARCHAR(9) NOT NULL,hire_date DATE NOT NULL);
INSERT INTO #target_updates (emp_id,hire_date)
VALUES ('PMA42628M','1979-03-15'),('PSA89086M','1988-12-22');
UPDATE
#employee
SET
hire_date=tu.hire_date
FROM
#employee AS e
INNER JOIN #target_updates AS tu ON
tu.emp_id=e.emp_id;
SELECT
*
FROM
#employee
ORDER BY
emp_id;
DROP TABLE #target_updates;
DROP TABLE #employee;
update table_name set='value' where orgid in (idnum1, idnum2)

Resources