我可以处理异常然后让它继续而不会导致代码中断吗?

时间:2012-06-27 16:03:28

标签: sql-server-2008 tsql exception-handling

我有一个存储过程(我没写过),它使用openquery来填充临时表。问题是我们有一个预期的错误(它命中一个不再存在的用户的活动目录),它正在停止整个过程。我希望做的是捕获错误,填写一些默认值并允许光标继续。目前,我正在捕捉错误,但proc正在停止。有没有办法可以强迫它继续下去?这是proc的一部分:

   BEGIN
        SET @SQL=N'INSERT INTO #AD_Display_Names (GUID, Display_Name) 
        SELECT objectGUID, displayName 
        FROM OPENQUERY(ADSI,''SELECT objectGUID, displayName 
        FROM ''''LDAP://<GUID=' + CONVERT (VARCHAR (MAX), @GUID) + '>'''' 
        WHERE objectCategory = ''''Person'''' AND objectClass = ''''user'''''')'

        BEGIN TRY
            EXEC SP_EXECUTESQL @SQL
        END TRY
        BEGIN CATCH
            SET @SQL=N'INSERT INTO #AD_Display_Names (GUID, Display_Name) 
            VALUES(''00000000-0000-0000-0000-000000000000'', ''Unknown'')'
            EXEC SP_EXECUTESQL @SQL
        END CATCH

        FETCH NEXT FROM [User_Names_Cursor]
        INTO @GUID
    END

1 个答案:

答案 0 :(得分:1)

为什么不做这样的事情?

- 光标在这里

BEGIN
    DECLARE @objectGUID UNIQUEIDENTIFIER
    DECLARE @displayName VARCHAR(100)
    SELECT @objectGUID = objectGUID, @displayName = displayName
    FROM OPENQUERY(ADSI, N'SELECT objectGUID, displayName 
                           FROM ''LDAP://<GUID=' + CONVERT (VARCHAR (MAX), @GUID) + '>''
                           WHERE objectCategory = ''Person'' AND objectClass = ''user'''

    IF(@objectGUID IS NULL)
    BEGIN
        SET @objectGUID = '00000000-0000-0000-0000-000000000000'
        SET @displayName = 'Unknown'
    END

    INSERT INTO #AD_Display_Names (GUID, Display_Name)
    VALUES(@objectGUID, @displayName)

    FETCH NEXT FROM [User_Names_Cursor]                           
    INTO @GUID  
END