当我更新表时,如何将count()作为条件?

时间:2015-06-15 08:25:03

标签: sql sql-server tsql

SELECT COUNT(TableID) 
FROM DiningTable
WHERE IsAvail = 1;

我可以在逻辑上得到“Number of Table”,但我想在下一个sql查询中使用该数字。

UPDATE DiningTable
SET IsAvail = 0
WHERE TableID = 11 - [Should be the number of Table, the result I get above];

我该怎么办?

2 个答案:

答案 0 :(得分:2)

如果第一个选择返回0行,请确保将isnull()检查以避免出现空错误

UPDATE DiningTable
SET IsAvail = 0
WHEN TableID = 11 - (SELECT ISNULL(COUNT(TableID),0) FROM DiningTable WHERE IsAvail = 1);

答案 1 :(得分:1)

UPDATE DiningTable
SET IsAvail = 0
WHEN TableID = 11 - (SELECT COUNT(TableID) FROM DiningTable WHERE IsAvail = 1);