更新列

时间:2012-12-11 13:26:54

标签: sql sql-update

我想在Peshwar表中添加性别。 我想在性别为空的Peshwar表的所有字段中添加性别, 由此查询返回

select  
    Gender_lookup_Table.
    Gender
from 
    Gender_lookup_Table,Peshwar
where 
    Gender_lookup_Table.initial_name like substring 
        (Peshwar.Student_Name, 1,CHARINDEX(' ',Peshwar.Student_Name,0))

使用它来填充性别栏:S但我不起作用。

update Peshwar
set 
gender=
    (
        select  
            Gender_lookup_Table.Gender
        from 
            Gender_lookup_Table,Peshwar
        where 
            Gender_lookup_Table.initial_name like substring
                 (Peshwar.Student_Name, 1,CHARINDEX(' ',Peshwar.Student_Name,0))
)
where gender= NULL

我需要一个for循环来填充所有列? :■

2 个答案:

答案 0 :(得分:2)

首先,与NULL值进行比较时,它应为IS NULL而不是= NULL

UPDATE  a
SET     a.gender = b.gender
FROM    peshwar a
        INNER JOIN gender_lookup_Table b
            ON b.initial_name LIKE SUBSTRING(a.Student_Name, 1, CHARINDEX(' ', a.Student_Name, 0))

答案 1 :(得分:2)

update p
SET p.gender = g.gender
FROM peshwar p
INNER JOIN Gender_lookup_Table g 
        ON g.initial_name LIKE SUBSTRING(p.Student_Name, 
                                         1,  
                                         CHARINDEX(' ', p.Student_Name,0))
WHERE p.gender IS NULL