Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

sql server - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...