Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check - Compare > Update SQL table

I would like to write a stored procedure where I can update a table based on following criteria.

Table 
EmployeeID  GroupID Group#
123     G123        3
456     G456        3
789     G789        3
101     G101        3

View
GroupID_Granular    GroupID_Middle  GroupID_Executive
G123            M123            E123
G789            M789            E789

If GroupID is found in View’s GroupID_Granular column, update the table, set GroupID = GroupID_Executive and set the Group# to 1.

I am not sure how to check/compare and then run Update cmd.

Thank you

like image 492
007 Avatar asked Mar 18 '13 18:03

007


People also ask

How do I check for an update in SQL?

SQL UPDATE Syntax To use the UPDATE method, you first determine which table you need to update with UPDATE table_name . After that, you write what kind of change you want to make to the record with the SET statement. Finally, you use a WHERE clause to select which records to change.

How can I compare two table values in SQL?

Comparing the Results of the Two Queries Let us suppose, we have two tables: table1 and table2. Here, we will use UNION ALL to combine the records based on columns that need to compare. If the values in the columns that need to compare are the same, the COUNT(*) returns 2, otherwise the COUNT(*) returns 1.

Can we use == in SQL?

As a result, SQL doesn't have the problem of ambiguity of = meaning either assignment or equality check. As a result, there is no problem with using = to check equality. On the other hand, in a programming language such as Java, single = is used for assignments, while == is used for comparison.


1 Answers

This can be done easily with a JOIN:

UPDATE t
SET 
    t.GroupID = v.GroupID_Executive, 
    t.[Group#] = 1
FROM YourTable t
JOIN YourView v ON v.GroupID_Granular = t.GroupID 

Sql Fiddle Here

like image 90
Michael Fredrickson Avatar answered Sep 22 '22 21:09

Michael Fredrickson