-1

我的程序有问题,我的代码中没有发现错误。我认为这是因为 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
4

1 回答 1

2

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

所以移动:

SET @ParmDefinition = N'@FeatureID int '

直到proc的顶部,然后调用

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

对于两条动态 SQL。


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


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

于 2013-01-30T15:32:24.603 回答