UPDATE table with values from table in a different DB - sql

Just started using SSMS and having difficulties getting simple SQL commands to work. I have tried using the Import/Export Wizard, but it won't work as the destination table have columns that aren't available in the source column, and those columns don't allow NULL values.
So, I need to write a SQL command where I can specify those column with values that aren't NULL. I believe the correct way to achieve this is to use UPDATE? I have been experimenting with just updating the Primary Key:
UPDATE db1.dbo.Customer
SET No_ = v4.No_
FROM db2.dbo.Customer as v4
When executing I get the following message:
(0 row(s) affected)

The basic idea for an update from two tables (regardless of database) in SQL Server would be something like this:
UPDATE c1
SET No_ = v4.No_
FROM db1.dbo.Customer c1 JOIN
db2.dbo.Customer v4
ON c1.CustomerId = v4.CustomerId;
In other words, you need to identify how the rows match between the two tables, and then you can set values in one table to values in the other.

UPDATE db1.dbo.Customer
SET No_ = c1.No_
FROM db2.dbo.Customer as 'c1'
WHERE
db1.dbo.Customer.CustomerID = c1.CustomerID

Related

SQL Server MERGE with Insert subquery

I'm having trouble getting this compound insert to work in my MERGE statement between two tables (Ignore the when match condition, I know its bad practice). The issue I'm having is getting the ServerId field in the target table to fill. The Team field is filling fine but all of the rows have a null value for ServerId. I can't find an example online for this so I'm hoping someone can help. I don't seem to have any syntactical errors and I know the column 'ServerName' in the Source table is filled for all rows.
MERGE ApplicationTeams AS Target
USING TempApplicationTeams AS Source
ON (Target.ServerId = (SELECT ID from Servers WHERE Name='Source.ServerName') AND Target.Team = Source.Team)
WHEN MATCHED THEN
UPDATE SET Target.Team = Target.Team
WHEN NOT MATCHED BY TARGET THEN
INSERT (ServerId, Team) VALUES((SELECT ID from Servers WHERE Name='Source.ServerName'), Source.Team)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;
Thanks.
I think you should remove the single quoutes on the where clausule.
You wrote:
(SELECT ID from Servers WHERE Name='Source.ServerName')
But I think you should write this:
(SELECT ID from Servers WHERE Name=Source.ServerName)
And make sure the select id returns only one row otherwise the statement will fail
I hope it will be usefully

SQL update set table if value in table A is equals to value in table B

this query is working fine.
UPDATE data
SET unit_id='a3110a89'
WHERE unit_id='7d18289f';
Now, I need to run this query over 30 times
so I made csv file import it to the DB with this command:
COPY mytable FROM 'D:/test.csv' WITH CSV HEADER DELIMITER AS ','
Now I have table called my table with 2 columns OLD and NEW
i want to search the table "data" in column unit_id anywhere there if the value equals to the value in table "mytable.old" replace it with the value "mytable.new" on the same row.
I tried to run this query but I get an error:
UPDATE data
SET unit_id=(SELECT mytable."old" FROM public.mytable)
WHERE unit_id=(SELECT mytable."new" FROM public.mytable)
error:
more than one row returned by a subquery used as an expression
I think i'm just trying to do it in the wrong way...
thx for the help!
by the way Im using PostgreSQL
Your subqueries need to be correlated to the outer update:
UPDATE data
SET unit_id = (SELECT mytable."new" FROM public.mytable where data.old = mytable.old)
WHERE unit_id in (SELECT mytable."old" FROM public.mytable);
That is, set the unit_id to the "new" value, when you find the "old" value in the table.
Can you try like this,
UPDATE data A
SET A.unit_id=B.old
FROM (SELECT mytable."old",mytable."new" FROM public.mytable) B
WHERE A.unit_id=B.new
UPDATE data A
SET unit_id = B."old"
FROM public.mytable B
WHERE A.unit_id = B."new"
;
BTW: it looks like you also have old and new swapped in your question. Do you really want A's value to be set to B's old field?

SQL Server: copy data from one column to another column?

I have two tables with the same column anomaly_id. I want to copy the row of anomaly_id from the first table to the second table using this code
UPDATE amb.anamoly_log_update
SET anamoly_id = t2.anomaly_id
FROM amb.anamoly_log_update t1
INNER JOIN amb.anomaly_fee t2 ON t1.anamoly_id=t2.anomaly_id
Even after I did that it shows 0 rows affected, when there is data in amb.anomaly.fee (source table)
Please help
Edit: Comment from post: I just want to copy all the anamoly_id from amb.anamoly_fee to amb.anamoly_log_update. My code might be nonsensical. Please do review it.
To copy the id from anomaly_fee to anamoly_log_update use :
INSERT INTO anamoly_log_update (anamoly_id)
SELECT anamoly_id FROM anomaly_fee
with both columns it looks like that:
INSERT INTO anamoly_log_update (anamoly_id,PID)
SELECT anamoly_id,PID FROM anomaly_fee
You only would copy the data if they where in both tables .. and then there is nothing update because you do not change the data => 0 rows affected
ON t1.anamoly_id=t2.anomaly_id
please think about what you really want to do and change your description ..
Does amb.anamoly_log_update contain at least one row corresponding to the anamoly_id that's present in amb.anamoly_fee? You are trying to join on two tables on anamoly_id.
You need to provide other linkage between tables than t1.anamoly_id=t2.anomaly_id or the query will do nothing
merge into amb.anamoly_log_update as t1
using amb.anomaly_fee as t2
on t1.anamoly_id=t2.anomaly_id
when matched then
update set t1.anamoly_id = t2.anomaly_id

Update trigger with GROUP BY

I'm using insert-/update triggers to update a second table's column Price.
The insert trigger seems to work perfectly, but when I try to change a single record in SSMS, I get an error:
The row value(s) updated or deleted either do not make the row
unique or they alter multiple rows(2 rows).
This is my update-trigger:
CREATE TRIGGER [dbo].[trgUpdateMasterData] ON [dbo].[tabSparePartMasterData_Temp]
AFTER UPDATE
AS
UPDATE tabSparePart
SET Price = MD.Price
FROM tabSparePart INNER JOIN
(
SELECT inserted.[Material Number (SAP)] AS MaterialNumber, inserted.Price
FROM inserted
GROUP BY [Material Number (SAP)], inserted.Price
) MD
ON tabSparePart.SparePartName = MD.MaterialNumber
I need to group by Material-Number because there are redundant rows inserted into table tabSparePartMasterData_Temp which i'm only using to update the Sparepart-Price in tabSparePart. But i assumed that the group by would sort out the duplicates(Price is same for any duplicate).
It's possible that the inserted/updated records' MaterialNumber is not available in tabSparepart. In this case this record should be "skipped". Does the INNER JOIN takes that into account?
Try adding SET NOCOUNT ON to the trigger
This error doesn't look like a SQL error and I'm guessing the client code is getting confused by the 2nd update in the trigger.
Edit: this error can be caused by the data grid view in SSMS being silly.
This isn't a SQL message as I thought: it is an SSMS being stupid message
See these which all says "learn to write SQL"
http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/dealing-with-the-row-value-s-updated-or (Less than dot blog)
Trigger that modifies multiple rows on diffrent table then it was invoked on in SQL Server 2005
SSMS permits duplicate records in a table, but not subsequent updates
Saying that, there is a KB article about a bug in SQL Server 2005...

How to update multiple rows in the same table of MySQL with PHP?

If only one row with a distinct field is to be updated,I can use:
insert into tab(..) value(..) on duplicate key update ...
But now it's not the case,I need to update 4 rows inside the same table,which have its field "accountId" equal to $_SESSION['accountId'].
What I can get out of my mind at the moment is:
delete from tab where accountId = $_SESSION['accountId'],
then insert the new rows.
Which obviously is not the best solution.
Has someone a better idea about this?
Use the update just like that!
update tab set col1 = 'value' where accountId = $_SESSION['accountId']
Moreover, MySQL allows you to do an update with a join, if that makes your life a bit easier:
update
tab t
inner join accounts a on
t.accountid = a.accountid
set
t.col1 = 'value'
where
a.accountname = 'Tom'
Based on your question, it seems like you should review the Update Statement.
Insert is used to put new rows in - not update them. Delete is used to remove. And Update is used to modify existing rows. Using "Insert On Duplicate Key Update" is a hackish way to modify rows, and is poor form to use when you know the row is already there.
load all of the values in to a temporary table.
UPDATE all of the values using a JOIN.
INSERT all of the values from the temp table that don't exist in the target table.
You can use replace statement. This will work as a DELETE followed by INSERT