M.Malatsi
M.Malatsi

Reputation: 21

Calling one procedure in another

I have created a stored procedure to check if a column has a value or not. If the column has a value it returns 1 and if not it returns -1.
Here is the code:

CREATE PROCEDURE [dbo].[sp_addPermissions](@groupName NVARCHAR(20), @column NVARCHAR(20))
AS
    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @CountDef NVARCHAR(MAX)
    DECLARE @FieldCount INT

    IF EXISTS(SELECT * FROM addPermissions WHERE groupName = @groupName)
    BEGIN
        IF EXISTS(SELECT * FROM sys.columns WHERE NAME = @column AND OBJECT_ID = OBJECT_ID(N'addPermissions'))
        BEGIN 
                SET @SQL=N'SELECT @Count=count(*) 
                         FROM addPermissions 
                         WHERE '+ quotename(@column) + ' IS NOT NULL
                         AND groupName = @groupName'

                         EXEC sys.sp_executesql @SQL, N'@groupName VARCHAR(20), @Count INT OUTPUT' , 
                             @groupName= @groupName, 
                             @Count = @FieldCount OUTPUT
                         --SELECT(@SQL)
                         select @FieldCount
                         IF(@FieldCount = 0)
                         BEGIN
                              RETURN -1
                         END
                         ELSE
                         BEGIN
                              RETURN 1
                         END
        END
        ELSE
        BEGIN
            RAISERROR('Column does not exist', 16, 1)
        END
    END
    ELSE
    BEGIN
        RAISERROR('Group do not have permission', 16, 1)
    END

I created the second procedure which calls the first procedure.
Code:

CREATE PROCEDURE getAddPermissions(@username NVARCHAR(40), @column NVARCHAR(20))
AS
    DECLARE @sSQL NVARCHAR(20)
    IF EXISTS(SELECT * FROM userLogin WHERE username = @username)
    BEGIN
        SELECT @sSQL = userGroup.groupName FROM userGroup 
        INNER JOIN userLogin
        ON userGroup.groupName = userLogin.groupName
        WHERE userLogin.username = @username

        EXEC sp_addPermissions @sSQL, @column
    END
    ELSE
    BEGIN
        PRINT 'User ' + @username + ' does not exist.'
    END

when I execute the first procedure it works fine, it returns 1 or -1. But when I execute the first procedure in the second procedure it returns 0, it does not return 1 or -1.

Upvotes: 0

Views: 36

Answers (1)

Sean Pearce
Sean Pearce

Reputation: 1169

EXEC @ReturnValue = sp_addPermissions @sSQL, @column

Upvotes: 1

Related Questions