存储过程中的游标转换失败

时间:2013-02-22 12:26:10

标签: sql-server types cursor

输入111111101,102,103,104

我想检查用户是否有权访问此请求...

我尝试了如图所示的游标,但是我收到了这个错误:

  将varchar值'101,102,103,104'转换为数据类型int时

转换失败。

代码:

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

提前致谢

1 个答案:

答案 0 :(得分:1)

根据您的SQL-Server版本,您可以使用像这个简短示例中的表值函数

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

定义为

的功能
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