Rohit
Rohit

Reputation: 69

Conversion failed in cursor in stored procedure

Input like 111111 and 101,102,103,104

I want to check whether user has access on this requests or not...

I tried a cursor as shown, but I get this error:

Conversion failed when converting the varchar value '101,102,103,104' to data type int.

Code:

ALTER PROCEDURE [dbo].[ValidateRqstId]
    @UserID VARCHAR(50),
    @RsqtIDs VARCHAR(300)
AS
BEGIN
   Declare @RqstId int
   Declare @Result int
   Declare @UserIDToCheck VARCHAR(50)
   Declare @RqstUserVal cursor for  
               Select RequestId 
               from REQUEST_LIST  
               where RequestId in (@RsqtIDs)

   BEGIN

      OPEN RqstUserVal
      FETCH NEXT from RqstUserVal into @RqstId

      WHILE(@@fetch_status <> -1)
      BEGIN
        SET @UserIDToCheck = (
               select UserId from dbo.REQUEST_LIST where RequestId =  @RqstId)

        Print(@UserIDToCheck)

        If(@UserIDToCheck != @UserID)
            SET @Result = 99 ;

        --Fetch the next row from the cursor
        FETCH RqstUserVal into @RqstId
      END
   END

   CLOSE RqstUserVal
   Deallocate RqstUserVal

   RETURN @Result 
END

Thanks in advance

Upvotes: 2

Views: 477

Answers (1)

bummi
bummi

Reputation: 27377

Depending on your SQL-Server Verion you can use a Table-Valued Function like in this short example

Select * from dbo.test1
Where ID in(
Select * from dbo.F_SplitAsIntTable('1,123,234,456'))

Function defined as

CREATE FUNCTION F_SplitAsIntTable 
(
@txt varchar(max)
)
RETURNS 
@tab TABLE 
(
 ID int
)
AS
BEGIN
    declare @i int
    declare @s varchar(20)
    Set @i = CHARINDEX(',',@txt)
    While @i>1
        begin
          set @s = LEFT(@txt,@i-1)
          insert into @tab (id) values (@s)
          Set @txt=RIGHT(@txt,Len(@txt)-@i)
          Set @i = CHARINDEX(',',@txt)
        end
    insert into @tab (id) values (@txt) 
    RETURN 
END
GO

Upvotes: 1

Related Questions