Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help me to write a query of foll scenarion:

i have tow tables in sql, one is "TABLE1" it contains a field "NAMES" thats contains list of names of about 500 persons.

other table is of "TABLE2", one field is "NAMES OF STUDENTS" and other is "GENDER" .

i want to match the names of "Table2" with "TABLE1" and if match is found, than the query will add "male" in gender column.
Posted

If I read you correctly, your TABLE1 is a list of males, while TABLE2 is a list of students of both genders, so if table 1 contains the name of a student, then that student is a male and you want to update the column?

Update table2
Set Gender = 'male'
where exists
(
select 1 from table1 where table1.name = table2.name
)
 
Share this answer
 
Comments
Toniyo Jackson 6-Jul-11 2:41am    
Perfect +5
Try this
select *, 'Male' as [Gender] from Table1 inner join Table2 on Table1.Name = Table2.Name


OR

select *, case when Table_2.Name is null then NULL else 'Male' end from Table_1 left join Table_2 on Table_1.Name = Table_2.Name
 
Share this answer
 
v2
Try this...

 If Exists(select T1.Name from table1 T1 left join table2 T2
       on T1.name=T2.Name)
 begin
 DECLARE @Name varchar(100);
 select @Name= T1.Name from table1 T1 left join table2 T2
    on T1.name=T2.Name
 update table2 set gender='male' where Name=@Name;
end
 
Share this answer
 
Thats great Deepthi! thanks. it works but updated only one row
but if we extend solution to %, means Azhar Khan is the full name, but if i have only Azhar in table2, it will match entire name, i want to modify it to 'azhar%'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900