将表名作为参数传递给存储过程

时间:2017-11-27 17:39:46

标签: sql-server stored-procedures parameters

这是我的存储过程,这是有效的:

/* 
    @CRM_Ref - This is the only required input port for this SP
    @North_Ref - Output port, returns the North_Ref for a valid CRM_Ref input
    @Output_Message - Output port, Returns the output of the SP, either 'Success' or 'North_Ref not found'
*/

ALTER PROCEDURE [dbo].sp_Get_North_Reference 
    @CRM_Ref NVARCHAR(255), 
    @North_Ref VARCHAR(255) OUTPUT, 
    @Output_Message VARCHAR(255) OUTPUT
AS
    DECLARE @var_North_Ref VARCHAR(255); -- Variable used to store the North_Ref
    DECLARE @var_Output_Message VARCHAR(255); -- Variable to carry the Output_Message
    DECLARE @COUNTER INT; -- Counter for the amount of times the while loop should run

    SET @COUNTER = 100;

    -- Loop will run 10 times with a 10 second delay between each loop
    WHILE @COUNTER >= 1
    BEGIN
        SET @var_North_Ref = (SELECT TOP 1 North_Ref FROM DEV.dbo.Address__ADDRESS WHERE CRM_Ref =  @CRM_Ref ORDER BY PUBLICATION_INSTANCE_DATE DESC)
        IF @var_North_Ref IS NULL
        BEGIN
            SET @COUNTER = @COUNTER - 1; -- Counter is decremented by 1
            SET @var_Output_Message = 'North_Ref not found';
            WAITFOR DELAY '00:00:10'; -- Wait is triggered if no North_Ref is found
        END
        ELSE
        BEGIN
            SET @COUNTER = 0; -- Counter is set to 0 to end the while loop
            SET @var_Output_Message = 'Success';
        END
    END

SET @Output_Message =  @var_Output_Message; -- Format Output_Message
SET @North_Ref = @var_North_Ref; -- Format North_Ref

;

GO

我想在此存储过程(@TableName VARCHAR(255))中添加另一个参数,我想将其传递给SELECT语句。

所以我想要像:

SELECT TOP 1 North_Ref 
FROM @Table_Name 
WHERE CRM_Ref =  @CRM_Ref 
ORDER BY PUBLICATION_INSTANCE_DATE DESC

我已经尝试过这样做但是我遇到了错误,因为我认为你不能在存储过程中使用参数作为表名

0 个答案:

没有答案