2011-11-30 103 views
0

我想在SQL Server中编写一个例程,运行时将遍历指定的表,如果特定的列包含值,则更新另一个值。在伪代码:SQL Server如果语句更新表值

select * from table1 
if column1 = true 
{ 
    update table2.column1 with value where table2.column2.value = table1.column2.value 
} 

基本上,遍历table1如果在一个特定的列值是true,更新另一个表的column1的值,其中该行的column2比赛table1column2

感谢

回答

3

您不需要IF,只需使用WHERE子句:

UPDATE T2 
SET t2.Column1 = 'blah' 
FROM Table2 t2 
INNER JOIN Table1 t1 
    ON t1.value = t2.value 
WHERE t1.column1 = 'True' 
0

不知道我完全理解你的要求,但如果你想使用一个更新语句更新所有的值,这可能做到:

update table2 set column1 = 
     (select column1 from table1 t1 
     where t1.column2 = table2.column2 
     ) 
    where exists 
     (select * from table1 t1 
     where t1.column2 = table2.column2 and t1.column1 = true 
     ) 

它可以写,以避免第二子查询(EXISTS的条款)但解决方案是相当具体的方言。我相信这个人更有可能以一种不知名的方言接受。 (除了单词“真”...代替你想要的值,那里。)