Using SQL to determine if all records of a related table have the same value - sql

I'm trying to create a stored procedure that will update a record on one table depending on certain values in a related table:
MainTable contains a status field and is related to SubTable which also has a status field. I need to update the status of each record in MainTable where ALL of the related records in SubTable has the same status x. I've tried several queries but think I am going about it the wrong way. Any assistance would greatly be appreciated. Thanks.

for example having following tables :
Producer ( Code,Name,Status)
Goods ( GCode,PCode( Producer Code),Name,Status)
and Query :
Update Producer set Status=F
where not exists (select * from Goods where Status <> X and Goods.PCode= Producer.Code)

Try this :
Update schema.yourtable s set s.fieldtoupdate = (
Select e.Relationalfield from schema.RealtionalTable e where e.STATUSFIELD = s.STATUSFIELD);
Hope it helps

Related

Update SQL query in SQL Server

I have an issue where I need to update a field in a number of SQL Server tables. The customer Order ID needs to be updated on all records that do not follow the standard format "C000001" (a letter followed by numbers). There are approximately 300 records that need changed (carry over records from a previous database version), as well as the corresponding linked tables.
I am a bit rusty on my SQL, so would like to verify the commands.
My proposed commands
UPDATE Customer_Order
SET ID = CONCAT('X', ID)
WHERE ID not like 'c%';
UPDATE Customer_Order_Line
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';
UPDATE Quote_Order
SET Cust_Order_ID = CONCAT('X', Cust_Order_ID)
WHERE Cust_Order_ID not like 'c%';
etc... (I have approx 12 additional tables to update same as above)
Assistance is appreciated, thanks in advance.
More of a formatted comment here..
Any time you want to do this, just make your update a select to verify your update:
SELECT ID, CONCAT('X', ID) as NewID
FROM Customer_Order
WHERE ID not like 'c%'
Make sure the NewID column is what you want to replace ID with.

Sql Server - Update multiple rows based on the primary key (Large Amount of data)

struggling with this one, quite a lengthy description so ill explain best I can:
I have a table with 12 columns in, 1 being a primary key with identity_insert, 1 a foreign key , the other 10 being cost values, ive created a statement to group them into 5 categories, shown below:
select
(ProductID)ProjectID,
sum(Cost1)Catagory1,
sum(Cost2)Catagory2,
sum(Cost3 + Cost4 + Cost5 + Cost6 + Cost7) Catagory3,
sum(Cost 8 + Cost 9)Catagory4,
sum(Cost10)Catagory5
from ProductTable group by ProductID
ive changed the names of the data to make it more generic, they aren't actually called Cost1 etc by the way ;)
the foreign key can appear multiple times (ProductID) so in the above query the related fields are calculated together based upon this... Now what ive been trying to do is put this query into a table, which i have done successfully, and then update the data via a procedure. the problem im having is that all the data in the table is overwritten by row 1 and when theres is thousands of rows this is a problem.
I have also tried putting the above query into a view and the same result... any suggestions would be great :)
update NewTable set
ProductID = (ProductView.ProductID ),
Catagory1 = (ProductView.Catagory1 ),
Catagory2 = (ProductView.Catagory2 ),
Catagory3 = (ProductView.Catagory3 ),
Catagory4 = (ProductView.Catagory4 ),
Catagory5 = (ProductView.Catagory5 )
from ProductView
I need something along the lines like above.... but one that doesn't overwrite everything with row 1 haha ;)
ANSWERED BY: Noman_1
create procedure NewProducts
insert into NewTable
select ProductID.ProductTable,
Catagory1.ProductView,
Catagory2.ProductView,
Catagory3.ProductView,
Catagory4.ProductView,
Catagory5.ProductView
from ProductView
inner join ProductTable on ProductView.ProductID = ProductTable.ProductID
where not exists(select 1 from NewTable where ProductView.ProductID = NewTable.ProductID)
above procedure locates the new Product that has been created within a view, the procedure query detects that there is a Product that is not located in the NewTable and inserts it via the procedure
As far as i know, and since you want to update all the products in the table, and each product uses all the sums of the product itself from origin, you actually need to update each row 1 by 1, and as consecuence when you do an update like the next, its your only main way
update newtable
set category1 = (select sum(cost1) from productTable where productTable.productId = newtable.ProductID),
category2 = (select sum(cost2) from productTable where productTable.productId = newtable.ProductID),
etc..
Keep in mind that if you have new products, they wont get inserted with the update, you would need like this in order to add them:
Insert into newtable
Select VALUES from productTable a where productId not exists(select 1 from newTable b where a.ProductId = b.ProductId);
A second way, and since you want allways to update all the data, is to simply truncate and do a insert select right after.
Maybe on an Oracle, you would be albe to use a MERGE but im unaware if it would really improve anything.
I asume that simply having a view would not work due the amount of data you state you have.
EDIT, I never knew that the MERGE STATMENT is actually avaiable on SQL Server 2008 and above, with this single statment you could do an UPDATE/INSERT on all but it's efficiency is unknown to me, you may want to test it with your high amount of data:
MERGE newtable AS TARGET
USING select ProductId, sum(cost1) cat1, sum(cost2) cat2 ...
FROM productTable Group by ProductId AS SOURCE
ON TARGET.ProductId = SOURCE.ProductID
WHEN MATCHED
THEN UPDATE SET TARGET.category1 = cat1, TARGET.category2 = cat2...
WHEN NOT MATCHED
THEN INSERT (ProductId, category1, category2,...)
VALUES (SOURCe.ProductId, SOURCE.cat1, SOURCE.cat2...);
More info about merge here:
http://msdn.microsoft.com/library/bb510625.aspx
The example at the end may give you a good overview of the sintax
You haven't given any join condition. SQL Server cannot know that you meant to update rows matched by productid.
update NewTable set
ProductID = (ProductView.ProductID ),
Catagory1 = (ProductView.Catagory1 ),
Catagory2 = (ProductView.Catagory2 ),
Catagory3 = (ProductView.Catagory3 ),
Catagory4 = (ProductView.Catagory4 ),
Catagory5 = (ProductView.Catagory5 )
from NewTable
join ProductView pv on NewTable.productid = pv.productid
You don't need a view. Just past the view query to the place where I said ProductView. Of course, you can use a view.

Periodic table update from another table

In this example, I have two tables in my DB. Table A receives data via SSIS from an external DB once a day. This information then needs to update records on Table B. The tables are joined by a two part primary key.
Table A
Mref
Rref
HD_Status
SL_Status
JB_Status
Table B
MrefIn
RrefIn
HD Status
SL Status
JB Status
The keys link by Mref = mrefIn & Rref = RrefIn.
The update script I've written is
UPDATE dbo.Table A
set HD_Status = dbo.Table B.HD Status,
SL_Status = dbo.Table B.SL Status,
JB_Status = dbo.Table B.JB Status
from dbo.Table B
where dbo.Table A.Mref = dbo.Table B.MrefIn AND
dbo.Table A.Rref = dbo.Table B.RrefIn
My question is: what is the best way to run this script, once a morning at 6am? I'm thinking SSIS but not exactly sure if this is the best practice. There should be no more than 1000 records to update.
Any replies are greatly appreciated!
Steve
A scheduled Stored Procedure was the way to go.
Thanks.

SQL Update from one table to another, and in some instances creating a new record where data doesnt exist

I have imported some data into a new sql table and have managed to update the imported data into the correct table but its unable to update for records without a customer number, i have tried updating the customer number but it says it cant update a primary key record.
This is the code i used to update the fields so far...
update SalBudgetCust
Set
SalBudgetCust.Sales1 = SalBudgetCust_temp.Sales1,
SalBudgetCust.Sales2 = SalBudgetCust_temp.Sales2,
SalBudgetCust.Sales3 = SalBudgetCust_temp.Sales3,
SalBudgetCust.Sales4 = SalBudgetCust_temp.Sales4,
SalBudgetCust.Sales5 = SalBudgetCust_temp.Sales5,
SalBudgetCust.Sales6 = SalBudgetCust_temp.Sales6,
SalBudgetCust.Sales7 = SalBudgetCust_temp.Sales7,
SalBudgetCust.Sales8 = SalBudgetCust_temp.Sales8,
SalBudgetCust.Sales9 = SalBudgetCust_temp.Sales9,
SalBudgetCust.Sales10 = SalBudgetCust_temp.Sales10,
SalBudgetCust.Sales11 = SalBudgetCust_temp.Sales11,
SalBudgetCust.Sales12 = SalBudgetCust_temp.Sales12
From
SalBudgetCust_temp where SalBudgetCust.Customer = SalBudgetCust_temp.Customer
Would anyone be able to offer some light on how if the customer record doesnt exist already it populates from the other table and then includes the corresponding sales figures?
Try SELECT INTO statement as below for inserting records where customer doesnt exist:
SELECT * INTO SalBudgetCust FROM SalBudgetCust_temp WHERE NOT EXISTS (SELECT Customer FROM SalBudgetCust WHERE Customer = SalBudgetCust_temp.Customer)
This SO Answer might also help you to the solution:
How to avoid duplicates in INSERT INTO SELECT query in SQL Server?

Update with multiple rows

i am using UPDATE to update all records in the table with value from another table:
UPDATE x.ADR_TEMP SET LOCATIONID = (SELECT ID FROM x.OBJECTRELATIONSHIP WHERE PROPERTYCLASS = 'PHYSICALLOCATION')
in both tables are the same number of records. I just need to read id from one table and put them into another.
I have error: ORA-01427: single-row subquery returns more than one row
I am new in this subject and suspect that solution is very simple. Please help me
UPDATE x.ADR_TEMP SET LOCATIONID = (
SELECT ID
FROM x.OBJECTRELATIONSHIP
WHERE PROPERTYCLASS = 'PHYSICALLOCATION' AND x.ADR_TEMP.relatedKey = x.OBJECTRELATIONSHIP.relatedKey )
if your tables are related to each other with some way like this(relatedKey is a column which relates to the second table mentioned), you can try this one.(not sure or perfect)