存储过程在While循环中选择语句

时间:2016-10-25 10:10:24

标签: sql sql-server stored-procedures procedure

我想在While循环中执行我的选择查询,但它不起作用。

Set @i = 1
    While(@i <= @rowNumber) 

    BEGIN

       Set @q_getoldeMail =  'SELECT Lower('+@columnname+') FROM (
      SELECT ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
          ,ID
          ,[Name]
          ,[Description]
          ,[Status]
          ,[AssignedTo]
          ,[AssignedToMail]
          ,[CC]
      FROM ' + QUOTENAME(@tablename) + ') AS ar Where rownumber = '+@i+''

    exec sp_executesql @q_getoldeMail, N'@get_oldeMail nvarchar(100) output', @get_oldeMail output

      Set @i = @i+1

在其他方面,我尝试执行查询而不使用while循环:

Set @q_getoldeMail =  'SELECT Lower('+@columnname+') FROM (
          SELECT ROW_NUMBER() OVER (ORDER BY ID) AS rownumber
              ,ID
              ,[Name]
              ,[Description]
              ,[Status]
              ,[AssignedTo]
              ,[AssignedToMail]
              ,[CC]
          FROM ' + QUOTENAME(@tablename) + ') AS ar Where rownumber = '+@i+''

        exec sp_executesql @q_getoldeMail, N'@get_oldeMail nvarchar(100) output', @get_oldeMail output

它也不起作用。我的错是什么?有没有办法通过While循环从Select语句中获取值?你能救我吗?

编辑:

我在此代码部分设置了@rowcount值:

SET @q_getrowNumber = 'SELECT Count(ID)
FROM dbo.' + quotename(@tablename) + ''

execute sp_executesql @q_getrowNumber, N'@rownumber int output', @rownumber output

此代码部分返回值(112)。但是当我改变@rowcount

Set @rowcount = 2

然后代码工作。我尝试转换为整数@rowcount但它没有工作

1 个答案:

答案 0 :(得分:0)

可能这就是你要找的东西 -

arg