检查存储过程是否有效

时间:2013-01-30 15:29:49

标签: sql-server stored-procedures

我的程序有问题,但我的代码中没有发现错误。我认为这是因为StopProc。任何人都可以检查我的存储过程以查看它是否有效?

ALTER PROCEDURE dbo.Update_FeatureUsers 
    (
        @FeatureID int,
        @UserID nvarchar (MAX),
        @CreatedUserID int
    )

AS
    SET NOCOUNT ON

    Declare @ParmDefinition nvarchar (400)
    Declare @Query nvarchar(MAX)

    SET @Query = N''
    SET @Query = @Query + N'DELETE FeatureUsers '
    SET @Query = @Query + N'FROM FeatureUsers '
    SET @Query = @Query + N'WHERE FeatureUsers.FeatureID = @FeatureID '
    SET @Query = @Query + N'    AND FeatureUsers.UserID NOT IN ('+ @UserID +')'

    EXECUTE sp_executesql @Query

    SET @Query = N''
    SET @Query = @Query + N'INSERT INTO FeatureUsers (FeatureID, UserID, CreatedUserID) '
    SET @Query = @Query + N'SELECT @FeatureID, Usager.UserID, @CreatedUserID '
    SET @Query = @Query + N'FROM Usager WITH (NOLOCK) '
    SET @Query = @Query + N'WHERE Usager.UserID IN ('+ @UserID +') '
    SET @Query = @Query + N'    AND Usager.UserID NOT IN '
    SET @Query = @Query + N'    ( '
    SET @Query = @Query + N'        SELECT FeatureUsers.UserID '
    SET @Query = @Query + N'        FROM FeatureUsers WITH (NOLOCK) '
    SET @Query = @Query + N'        WHERE FeatureUsers.UserID IN ('+ @UserID +') '
    SET @Query = @Query + N'            AND FeatureUsers.FeatureID = @FeatureID '
    SET @Query = @Query + N'    ) '

    SET @ParmDefinition = N'@FeatureID int '
    EXECUTE sp_executesql @Query, @ParmDefinition, @FeatureID = @FeatureID

    SET NOCOUNT OFF

    RETURN

1 个答案:

答案 0 :(得分:2)

您的第一个动态SQL查询也想访问@FeatureID,但您没有通过它。

所以搬家:

SET @ParmDefinition = N'@FeatureID int '

直到proc的顶部,然后调用

EXECUTE sp_executesql @Query,@ParmDefinition,@FeatureID = @FeatureID

两个动态SQL。


对于一般策略 - 如果你使存储过程接受@Users的表值参数然后根本不需要使用动态SQL,那会好得多。


实际上,在第二次阅读时,您的第二个查询也引用了@CreatedUserID,因此您需要将其作为参数传递给第二个查询。因此,您需要更改两者之间的参数定义,或者只是将其添加到参数中并将其(无意义地)传递给第一个查询。