In SQL Server, how can I change a column values depending on whether it contains a certain value? - sql

Sorry if the title is a bit confusing... I'm trying to fix some data. Here goes the explanation:
Say I have two tables.
The first is a lookup table that is no longer in use.
The second has one varchar(50) column that sometimes has product names and
sometimes has product ids from the old lookup table.
The idea is to convert all the PID values in the Product table into the product names. Here's a pic i made up to help illustrate it:
The lookup table is much larger, that's just an example. So i'd guess it would be an update statement that would use the ProductsLookup.Name value if the Product value was found to be in the ProductsLookup.PID set? How would this look in SQL?
Thanks much for the help,
Carlos

You need to put inner join with both these tables "ProductsLookup" and "Products" on PID and Product column. But Product column in "Products" table is varchar so you have to apply ISNUMERIC function on this column to make sure that join works fine. below is example
UPDATE
P
SET
P.Product=PL.Name
FROM
Products P
INNER JOIN ProductsLookup PL ON PL.PID=CASE WHEN ISNUMERIC(P.Product)=1 THEN P.Product ELSE -1 END

You can do this with an update and join:
update p
set product = pl.name
from products p join
productslookup pl
on pl.pid = p.id;
A left join is not needed, because you only need to update the values that match in the lookup table.
I will caution you that performance might be an issue. The problem is the types between the two tables -- presumably pid is a number not a string. If so, you can create a computed column to change the type and an index on that column.

Related

Inserting values from another table into a column where values are null

I have a table A with ID's only and another table B with two columns, ID and Product Number. The ID column in table B has nulls and Product Number has Product Numbers. I would like to update table B with the ID's in column in no specific order just so that the Product Number has ID's.
I have tried to use update but that has not worked, have tried insert but it just adds the ID's in A to the bottom of the list in B. Would like to do this in Microsoft SQL.
SQL code tried:
IF OBJECT_ID('tempdb..#ProductNum') IS NOT NULL DROP TABLE #ProductNum
SELECT ID
INTO #ProductNum
FROM Products
UPDATE [ProductCatalogue] PC
SET
PC.ID = Pn.ID
FROM #ProductNum Pn
INNER JOIN
[ProductCatalogue] PC
ON Pc.ID = Pn.ID
WHERE Pc.ID IS NULL
It sounds a lot like you would be better off having the ID-Column Autoincrement, instead of giving it the IDs from table A. This is already explained in this answer.
In case you actually need the specific IDs from table A, this SO thread might help you.
Solved the issue by creating auto increment columns on each table and called it Row_ID. Then I used Row_ID to join the tables together with some logic provided by #Chris above.

Refer to different id's within the same query in SQL

I need to brind a lot of columns from several tables using LEFT JOIN. My starting point is the orders table and I bring the vendor name from the "Address_table". Then I add another table with order details and then the shipping information of each order detail.
My problem is that I need to bring a different record from "Address_table" to refer onether id's detailed in shipment table as of "origin_id" and "destination_id".
In other words, "address_id", "origin_id" and "destination_id" are all records from "Address_table". I brought the first one related to the vendor, how can I retrieve the other two?
Example
Thanks in advance
Your question is not exactly clear in terms of the tables and their relationships. It is, however, clear what the problem is. You need to join against the same table twice using different columns.
In order to do that you need to use table aliases. For example, you can do:
select *
from shipment s
left join address_table a on a.address_id = s.origin_id
left join address_table b on b.address_id = s.destination_id
In this example the table address_table is joined twice against the table shipment; the first time we use a as an alias, the second time b. This way you can differentiate how to pick the right columns and make the joins work as you need them to.

SQL INNER JOIN without linked column

I have an UltraGrid displaying customer information in it. The way the database is set up, there are 2 tables. Customers and Customer_Addresses. I need to be able to display all of the columns from Customers as well as Town and Region from Customer_Addresses, but I'm under the impression that I'd need Town and Region columns in the Customer table to be able to do this? I've never used an INNER JOIN before so I'm not sure if this is true or not, so can anybody give me pointers on how to do this, or if I need the matching columns or not?
Does it even require an INNER JOIN, or is there an alternative way to do this?
Below are the design views of both of the tables - Is it possible to display Add4 and Add5 from Customer_Addresses with all of Customers?
As long as you have another key column you can use to link the tables (ex. ID_Column), it is better that you use LEFT JOIN.
Example:
SELECT c.col1, ... , c.colN, a.town, a.region FROM Customers c
LEFT JOIN Customer_Addresses a ON a.ID_Column = c.ID_Column
In order to clarify how JOIN types work, look at this picture:
In our case, using a LEFT JOIN will take all information from the Customers table, along with any found matching (on ID) information from Customer_Addresses table.
First of all you need some column in common in two tables, all what you have to do is:
CREATE TABLE all_things
AS
SELECT * (or columns that you want to have in the new table)
FROM Costumers AS a1
INNER JOIN Customer_Addresses AS a2 ON a1.column_in_common = a2.column_in_common
The point is what kind of join do you want.
If you can continue the process without having information in table Costumers or in table Customer_Addresses maybe you need OUTER JOIN or other kind of JOIN.

Multi update query

I've created two temp tables. One with Orders which contains Article and Quantity and the other one with availability where we also have Article and Quantity. I would like to write a multi update query with subtracking order quantity from stock and from itself for all articles in temporary table with Orders. As far as I know it is not possible to alter two fields from different tables in one update query.
I've tried something like this, but it's of course doesn't work.
UPDATE #Stocks as s
INNER JOIN #Orders as o on o.ArticleId=s.ArticleId
SET
s.Quantity = (s.Quantity - o.Quanity)
FROM
#Stocks s
JOIN #Orders o on o.ArticleId=s.ArticleId
WHERE
#Stocks.ArticleId IN (SELECT ArticleId FROM #Orders)
When do you an update using a join with multiple matches, only one arbitrary row is chosen for the update. The key idea is to aggregate the data before the update:
UPDATE s
SET Quantity = (s.Quantity - o.Quanity)
FROM #Stocks s JOIN
(SELECT o.ArticleId, SUM(o.Quantity) as quantity
FROM #Orders o
GROUP BY o.ArticleId
) o
ON o.ArticleId = s.ArticleId;
Your statement is way over-complicated, mixing update syntax from SQL Server, MySQL, and Postgres. In addition, the WHERE clause is unnecessary because the JOIN does the filtering. However, even once the syntax errors are fixed, you will still have the problem of calculating incorrect results, unless you pre-aggregate the data.
Unfortunately, the description of this behavior is buried deep in the documentation of the first example on the update page:
The previous example assumes that only one sale is recorded for a
specified salesperson on a specific date and that updates are current.
If more than one sale for a specified salesperson can be recorded on
the same day, the example shown does not work correctly. The example
runs without error, but each SalesYTD value is updated with only one
sale, regardless of how many sales actually occurred on that day. This
is because a single UPDATE statement never updates the same row two
times. [emphasis added]
How about this?
UPDATE s
SET s.Quantity = (s.Quantity - o.Quanity)
FROM #Stocks as s
INNER JOIN #Orders as o on o.ArticleId=s.ArticleId
For updating two tables using single query, you should create a view that contain both tables columns and then update that view.
Your Question is all about Multi Update,
but updation perform in one table based on another table so
to do this use join
But if updation perform in two or more table we have to create view then we can update
thanks

Update a field from one table to another, involving a 3 table join

I have a table I need to update the price field in. I need to update this field from a different price field from a different table. The only way I can get to the required table for the update is by joining another table into this query.
So in all I need to join 3 tables in the update.
Table A has the price field that needs to be updated. In this table I have the foreign key of the product.
Table A structure
-PK_TABLE_A,
-FK_TABLE_B,
-ITEM_COST,
-ITEM_PRICE (needs to be updated from Table C)
Table B is the product table which has the PK of the product. This table is used to access Table C.
I also need to filter Table B to only update a certain stock type.
Table B structure
-PK_TABLE_B,
-FK_TABLE_C,
-DESCRIPTION,
-QUANTITY,
-ITEM_TYPE (a string that needs to be added in where clause to only update records with certain type).
Table C has a foreign key back to Table B. It also contains the price field that I need to use to update the price field in table A
Table C structure
-PK_TABLE_C,
-FK_TABLE_B,
-PRICE (this is the field that I need to use to update the price field in table A)
-USED_DATE,
-ID
The DBMS I am using is Firebird.
I have tried to use sub queries to no avail. I regularly use a sub-select when using two tables to update, so something like
UPDATE table1 AS t1
SET t1.FK = (select table2.PK
FROM table2 INNER JOIN
table1
ON table2.FK = table2.PK
WHERE table2.name = t1.name)
I'm just struggling to use the same technique with a 3rd table incorporated.
I am not even sure if this is the correct way to go about this situation. I have looked on google, but most examples I have come across don't utilise the 3rd table.
Any help would be appreciated.
**edited to included more detail on table structure.
are you able to show us the table structures in more detail?
if both tableA and tableC have a foreign key that points back to tableB I don't think you need to include a three table join. you just need to
update tableA set ITEM_PRICE = SELECT(PRICE FROM TableC WHERE
TableA.FK_TABLE_B = TableC.FK_TABLE_B;
unless I'm missing something?
edited to reflect a better understanding of the problem
alright, I think I've got it this time:
update tableA set price =
(select price from tableC where tableA.fk_tableB = tableC.fk_tableB) where
(Select item_type from tableB where tableB.pk_tableB = tableA.fk_tableB) =
'$itemTypeVariable';
edited again with a better understanding of the problem