SQL过程 - 根据其他表的计数更改表列的值

时间:2012-05-30 11:38:44

标签: sql sql-server

我有两个表,propertycomponentcomponent.id_property = property.id

我正在尝试创建一个过程,该过程对所选属性上的组件进行计数,如果所选属性没有组件,则将property.id_state更改为1.

create PROCEDURE property_statement_change AS
BEGIN
declare @value int;

select 
    @value = count(c.value)
from
    component c
where
    c.id_property = 1
group by c.id_property

IF (@value = 0)
  UPDATE property
  SET id_state = 1
  WHERE property.id = 1
END

如果我执行存储的produre,它不会改变任何东西,但是选择并且也可以正确更新。我做错了什么?

1 个答案:

答案 0 :(得分:2)

如同评论中所述,值为NULL而不是0,所以这里是代码:

create PROCEDURE property_statement_change AS
BEGIN
declare @value int;

select 
    @value = count(c.value)
from
    component c
where
    c.id_property = 1
group by c.id_property

IF (@value is NULL)
  UPDATE property
  SET id_state = 1
  WHERE property.id = 1
END