I am working with SQL Server 2008. I have 2 tables here.
shades_table color_name category location Aqua Blue House A Denim Blue House B Azure Blue House B Zaffre Blue House A Scarlet Red House C Ruby Red House D Chili Red House D Crimson Red House A objects_table object_name color_cat location2 Super Aqua shoes Null Null Azure wallet Null Null Awesome Scarlet chair Null Null Ruby socks Null Null Sparkly Denim chalk Null Null Chili paper Null Null Zaffre vase Null Null Sharp Crimson eraser Null Null Crimson watch Null Null Excellent Scarlet bucket Null
I have a reference table called shades_table. A column contains color_name, and the other column contains the category of the color.
I am working on the objects_table. The object_name column contains the color name. I would want a procedure/program to automatically match the color_names to the Object_name, and then update the Null values in the color_cat column.
My current method is to export the shades_table to a csv file. Then I wrote a Java program which reads the csv file, and output to a sql file to be run by the server:
UPDATE objects_table SET color_cat='Blue', location2 = 'House A' WHERE object_name LIKE '%Aqua%' AND color_cat IS NULL UPDATE objects_table SET color_cat='Blue', location2 = 'House B' WHERE object_name LIKE '%Denim%' AND color_cat IS NULL UPDATE objects_table SET color_cat='Blue', location2 = 'House B' WHERE object_name LIKE '%Azure%' AND color_cat IS NULL etc...
This method works, but it's stupid, cumbersome. I just don't know how to write the SQL statements which can do what I want.
Update: I have added an extra column which I also want to match.(Refer to my Java program output). UPDATE statement with 2 SET doesn't work. example
update o set o.color_cat = s.category, set o.location2 = s.location ...
doesn't work, gives "Incorrect syntax near the keyword 'set'.
Here is the update query.
UPDATE a
SET a.color_cat=b.category
FROM objects_table a
JOIN shades_table b ON a.[object_name] LIKE '%'+b.[color_name]+'%'
WHERE a.color_cat IS null
If you want it as a procedure
CREATE PROCEDURE Updateobjectstable
AS
BEGIN
UPDATE a
SET a.color_cat=b.category
FROM objects_table a
JOIN shades_table b ON a.[object_name] LIKE '%'+b.[color_name]+'%'
WHERE a.color_cat IS null
END
I don't see a reason to use procedure for this task. Plain SQL should work.
UPDATE objects_table ot
SET color_cat = st.category
FROM shades_table st
WHERE ot.object_name ILIKE concat('%', st.color_name, '%')
AND ot.color_cat IS NULL
Simple update
statement will do that for you:
update o
set o.color_cat = s.category
from objects_table o
left join shades_table s
on(o.[object_name] like '%' + s.color_name + '%')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.