用于检查存储过程是否存在的动态SQL

时间:2019-05-21 11:41:20

标签: sql sql-server stored-procedures dynamic-sql

我想使用动态SQL执行此查询,但是它不会影响@Exists变量。问题是什么?

目的:检查数据库@TransformProcName中是否存在名称为@TargetDb的存储过程:

SET @Sql = N'IF NOT EXISTS (SELECT *
                FROM ' + QUOTENAME(@TargetServer) + '.' + QUOTENAME(@TargetDB) + ' 
                WHERE type = ''P'' AND OBJECT_ID = OBJECT_ID(N'''+QUOTENAME(@TargetSchema)+'.'+QUOTENAME(@TransformProcName)+'''))
                    SET @Exists = 0
             ELSE
                    SET Exists = 1'

EXEC sp_executesql @Sql,N'@Exists bit OUTPUT', @Exists OUTPUT

1 个答案:

答案 0 :(得分:4)

您在这里有几个问题。首先,您有SET Exists = 1,应该为SET @Exists = 1,但是您还引用了无效的对象。您需要在此处使用sys.proceduressys.schemas,并且您不能使用OBJECT_ID,因为它将在您连接的数据库的上下文中运行。这为您提供了以下内容(还整理了动态SQL):

DECLARE @SQL nvarchar(MAX);

DECLARE @TargetServer sysname, @TargetDB sysname, @TargetSchema sysname, @TransformProcName sysname;

SET @TargetDB = N'Sandbox';
SET @TargetSchema = N'dbo';
SET @TransformProcName = N'sample_sp';

DECLARE @Exists bit;


SET @Sql = N'IF NOT EXISTS (SELECT *' + NCHAR(13) + NCHAR(10) +
           N'               FROM ' + QUOTENAME(@TargetServer) + N'.' + QUOTENAME(@TargetDB) + '.sys.procedures p' + NCHAR(13) + NCHAR(10) +
           N'                    JOIN sys.schemas s ON p.schema_id = s.schema_id' + NCHAR(13) + NCHAR(10) +
           N'               WHERE p.[name] = @TransformProcName' + NCHAR(13) + NCHAR(10) +
           N'                 AND s.[name] = @TargetSchema)' + NCHAR(13) + NCHAR(10) +
           N'       SET @Exists = 0' + NCHAR(13) + NCHAR(10) +
           N'ELSE' + NCHAR(13) + NCHAR(10) +
           N'       SET @Exists = 1;'


PRINT @SQl;
EXEC sp_executesql @Sql,N'@TransformProcName sysname, @TargetSchema sysname, @Exists bit OUTPUT', @TransformProcName = @TransformProcName, @TargetSchema = @TargetSchema, @Exists =  @Exists OUTPUT;
PRINT @Exists;