Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

Dynamic Sql Query with Output Parameters

I had a previous post on how to use Dynamic Sql Queries.

Today I had the need to create a Stored Procedure that returns an Output Parameter, where the value of the output parameter is set inside the Dynamic Query.

So here is a sample Stored Procedure that shows how to do s:

CREATE PROCEDURE GetNotificationIdByCustomerId
(
    @CustomerId    INT,
    @GroupId    INT,
    @NotificationId    INT OUTPUT
)
AS
BEGIN
    DECLARE @strQuery NVARCHAR(4000)
    DECLARE @parameterList NVARCHAR(4000)

    SELECT @strQuery = 
        N'SELECT 
            TOP 1 @NotificationId = NotificationId  
        FROM 
            Notifications
        WHERE (CustomerId = @CustomerId)  AND (Processed = 0) '

    IF ( @GroupId <> -1 )
    BEGIN
        SELECT @strQuery = @strQuery  + N' AND (GroupId = @GroupId)'
    END
    
    SELECT @parameterList =   N'@NotificationId INT OUTPUT, @CustomerId INT, @GroupId INT'            
    EXECUTE SP_EXECUTESQL @strQuery, @parameterList, @NotificationId OUTPUT, 
                @CustomerId = @CustomerId, @GroupId = @GroupId
END
GO

I need to get @NotificationId, which is set inside the dynamic query, I then supply a list of parameters inside the @parameterList, where I specify the output parameter.

Hope that helps,

Regards

Published Wednesday, February 15, 2006 4:13 AM by BilalHaidar [MVP]
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required)