我使用 Microsoft SQL Server 2012。我需要检查名为 SiteObjects
的表是否数据库中至少有一条记录,其中列名为 SiteRegionId
的值等于 22
.
如果是,它必须实现一些逻辑,否则它必须实现另一个逻辑。
这是我的实现:
IF EXISTS (SELECT * FROM SiteObjects WHERE SiteRegionId = 22)
BEGIN
----do what you need if exists
RETURN '0'; --not deleted
END
ELSE
BEGIN
--do what needs to be done if not
DELETE FROM SiteRegions
WHERE Id = 22;
RETURN '1';
END
我认为这一行:
SELECT * FROM SiteObjects WHERE SiteRegionId = 22
无效,因为据我了解它在所有表行上运行并选择所有行
SiteRegionId
等于22。有什么办法可以让它更有效?并检查是否 任何 该行的满足条件,如果是,则继续。
最佳答案
不,EXISTS
足够聪明,一旦观察到一行就返回真。并且系统知道实际上没有检索到任何列数据。
早在 90 年代,一些优化器和数据库系统还不够聪明,无法识别这种情况,但我不知道现在有任何可以实际检索所有数据的系统。 (当然,对于SQL Server线,在产品2000版之前就修复了)
因此,其他答案中的建议是十多年前遗留的建议。
见 Subqueries with Exists :
The subquery does not actually produce any data
...
- The select list of a subquery introduced by EXISTS almost always consists of an asterisk (*). There is no reason to list column names because you are just testing whether rows that meet the conditions specified in the subquery exist.
关于sql-server - 如何检查SQL列是否有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39096061/