我不知道如何解决这个错误:
Conversion Failed when converting the varchar value
‘SELECT LastName,FirstName FROM ##Results WHERE ##RowNum BETWEEN(‘ to data type int.
查询是:
SET @s_query = 'SELECT ' + @ColNames1 + ' FROM ##Results WHERE ##RowNum BETWEEN('+@PageIndex1+'-1) * '+@PageSize1+' + 1 AND((('+@PageIndex1+' -1) * '+@PageSize1+' + 1) + '+@PageSize1+') - 1';
解决方法
您正在构建一个字符串并将其结果放在@s_query变量中.
因此,您必须以这种方式将int变量转换为@ PageIndex1和@ PageSize1:
SET @s_query = 'SELECT ' + @ColNames1 + ' FROM ##Results WHERE ##RowNum BETWEEN('+CONVERT(varchar(20),@PageIndex1)+'-1) * '+CONVERT(varchar(20),@PageSize1)+' + 1 AND((('+CONVERT(varchar(20),@PageIndex1)+' -1) * '+CONVERT(varchar(20),@PageSize1)+' + 1) + '+CONVERT(varchar(20),@PageSize1)+') - 1';
如果要保持代码的可读性,可以定义两个变量:
DECLARE @pistr varchar(20) DECLARE @psstr varchar(20) SET @pistr = CONVERT(varchar(20),@PageIndex1) SET @psstr = CONVERT(varchar(20),@PageSize1)
所以你的查询变为:
SET @s_query = 'SELECT ' + @ColNames1 + ' FROM ##Results WHERE ##RowNum BETWEEN('+ @pistr +'-1) * '+@psstr+' + 1 AND((('+@pistr+' -1) * '+@psstr+' + 1) + '+@psstr+') - 1';