I have problem in my program and I didn’t find error in my code. I think it’s because StopProc. Can anybody check my stored procedure to see if it is valid?
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
Your first dynamic SQL query also wants to access
@FeatureID, but you’re not passing it.So move:
Up to the top of the proc and then call
for both pieces of dynamic SQL.
For the general strategy – it would be far better if you made the stored proc accept a table-valued parameter for
@Usersand then you wouldn’t need to use dynamic SQL at all.Actually, on second reading, your second query also references
@CreatedUserID, so you’ll need to pass that across as a parameter to the second query. So you need to change the parameter definition between the two, or just add it to the parameters and pass it (pointlessly) to the first query.