SQL如何通过遍历表来检查存储过程是否存在

时间:2018-12-17 16:45:17

标签: sql-server sql-server-2016

假设我有一个表,该表在SQL Server 2016中具有列Name, Date, StoredProcedure

我需要查询该表并遍历存储过程列,并检查该存储过程是否存在于数据库中。如果它不存在,那么我只需要将该行设置为存储过程列为空。

这是我尝试过的方法,但是不起作用

Select m1.StoredProcedure 
from MyTable m1 
where
    IF NOT EXISTS (SELECT  *
                   FROM sys.objects
                   WHERE object_id = OBJECT_ID(N'StoredProcedure')
                     AND type IN (N'P', N'PC')) 
    Then Update MyTable m2
         Set StoredProcedure = ''
         Where m2 StoredProcedure = m1.StoredProcedure

2 个答案:

答案 0 :(得分:5)

我怀疑您所追求的是:

UPDATE MT
SET StoredProcedure = NULL
FROM MyTable MT
     LEFT JOIN sys.procedures p ON MT.StoredProcedure = p.[name]
WHERE p.object_id IS NULL;

还要注意,''NULL是不同的。在示例SQL中,您有Set StoredProcedure = '',但是,您在问题中声明“我需要为存储过程列将此行设置为空” 。我假设,您确实想要NULL而不是空字符串('')。

答案 1 :(得分:0)

尽管@Larnu的答案是正确的,但我想提供另外两个简单的方法

update mt
set StoredProcedure = NULL
from MyTable mt
where object_id('StoredProcedure') is null;

-- or
-- at the suggestion of Larnu comment 
update MyTable
set StoredProcedure = case when object_id('StoredProcedure') is null then null else StoredProcedure end
相关问题