在存储过程中切换用户定义的列名称或默认列名称的最佳方法是什么

时间:2014-12-16 12:07:26

标签: sql-server

存储过程在用户定义的列名称或默认列名称之间切换的最佳方法是什么

这是我到目前为止所做的。这适用于小型查询,对于更大的查询,有更好的方法吗?

-- Drop stored procedure if it already exists
IF EXISTS(SELECT * FROM sys.procedures 
        WHERE schema_id = schema_id('dbo')
        AND name = N'sp_test')
    DROP PROCEDURE dbo.sp_test
GO

CREATE PROCEDURE [dbo].[sp_test]
    -- /* Declare parameters */
    @columnName BIT =0
AS
BEGIN
    -- SELECT statement to fetch record
    IF(@columnName =1)
        (
            SELECT
                TOP 100
                IM.INC_REF,
                IM.ID
            FROM
                dbo.TEST AS IM
        )
    ELSE
        (
            SELECT
                TOP 100
                IM.INC_REF AS REF,
                IM.ID AS ID
            FROM
                dbo.TEST AS IM
        )
END
GO

-- ============================================
-- Execute stored procedure
-- ============================================

DECLARE @columnName AS BIT

SET @columnName =0


EXEC [dbo].[sp_test] @columnName

提前致谢

1 个答案:

答案 0 :(得分:0)

当我们需要基于参数的存储过程的不同结果时,我们将调用两个“子”存储过程之一。在你的情况下,那将是:

CREATE PROCEDURE [dbo].[sp_test]
    -- /* Declare parameters */
    @columnName BIT = 0
AS
    BEGIN
        IF ( @columnName = 1 )
            EXEC dbo.[sp_test1]
        ELSE
            EXEC dbo.[sp_test2]
    END
GO

CREATE PROCEDURE dbo.[sp_test1]
AS
    BEGIN
        SELECT TOP 100
                IM.INC_REF ,
                IM.ID
        FROM    dbo.TEST AS IM
    END
GO

CREATE PROCEDURE dbo.[sp_test2]
AS
    BEGIN
        SELECT TOP 100
                IM.INC_REF AS REF ,
                IM.ID AS ID
        FROM    dbo.TEST AS IM
    END

GO

我发现这可以解决严重缓存计划的问题。