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



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

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

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

您在这里有几个问题。首先,您有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;

相关内容

  • 没有找到相关文章

最新更新