代码之家  ›  专栏  ›  技术社区  ›  Chris Woodruff

如何在SQLServer2005ManagementStudio中创建SQLServer2005存储过程模板?

  •  7
  • Chris Woodruff  · 技术社区  · 16 年前

    3 回复  |  直到 15 年前
        1
  •  16
  •   binki    11 年前

    我认为另一个小金块将有助于人们开发数据库,提高数据库开发的效率。在开发软件解决方案时,我非常喜欢存储过程和函数。我喜欢在数据库级别实现我的实际CRUD方法。它允许我在应用软件(业务逻辑和数据访问)和数据库本身之间平衡工作。我不想挑起一场宗教战争,但我想让人们能够更快地开发存储过程,并通过模板使用最佳实践。

    让我们从在SQLServer2005ManagementStudio中创建自己的模板开始。首先,您需要在Studio中显示模板资源管理器。

    alt text http://www.cloudsocket.com/images/image-thumb10.png

    这将显示以下内容:

    alt text http://www.cloudsocket.com/images/image-thumb11.png

    alt text http://www.cloudsocket.com/images/image-thumb12.png

    alt text http://www.cloudsocket.com/images/image-thumb13.png

    IDE将创建一个空白模板。要编辑模板,请在模板上单击鼠标右键,然后选择“编辑”。您将在IDE中获得一个空白的查询窗口。现在可以插入模板实现。我这里有一个新存储过程的模板,其中包含一个TRY-CATCH。我喜欢在存储过程中包含错误处理。在SQLServer2005的TSQL中添加了新的TRY-CATCH,我们应该尝试通过我们的代码(包括数据库代码)来使用这种强大的异常处理机制。保存该模板,就可以使用新模板创建存储过程了。

    -- ======================================================
    -- Create basic stored procedure template with TRY CATCH
    -- ======================================================
    
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author:        <Author,,Name>
    -- Create date: <Create Date,,>
    -- Description:    <Description,,>
    -- =============================================
    CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
        -- Add the parameters for the stored procedure here
        <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
        <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
    AS
        BEGIN TRY
            BEGIN TRANSACTION    -- Start the transaction
    
            SELECT @p1, @p2
    
            -- If we reach here, success!
            COMMIT
        END TRY
        BEGIN CATCH
            -- there was an error
            IF @@TRANCOUNT > 0
            ROLLBACK
    
            -- Raise an error with the details of the exception
            DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
            SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
    
            RAISERROR(@ErrMsg, @ErrSeverity, 1)
        END CATCH
    GO
    
        2
  •  4
  •   Jorge Ferreira    16 年前

    你提出 使用Ctrl+Alt+T或槽 视图>模板浏览器

        3
  •  2
  •   Dhiraj    14 年前

    数据库=>表=>可编程性=>程序=>右键单击选择新程序