我不知道如何解决此错误:
转换varchar值时转换失败
' 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';
答案 0 :(得分:9)
DECLARE @s_query NVARCHAR(MAX);
DECLARE @ColNames1 NVARCHAR(MAX) = 'Some_Column'
DECLARE @PageIndex1 INT = 10;
DECLARE @PageSize1 INT = 20;
SET @s_query = N'SELECT ' + QUOTENAME(@ColNames1) + N' FROM ##Results
WHERE RowNum BETWEEN('+CAST(@PageIndex1 AS NVARCHAR)+ N'-1) * '
+ CAST(@PageSize1 AS NVARCHAR)+ N' + 1 AND((('+ CAST(@PageIndex1 AS NVARCHAR)+ N' -1) * '
+ CAST(@PageSize1 AS NVARCHAR)+ N' + 1) + '+ CAST(@PageSize1 AS NVARCHAR)+ N') - 1';
PRINT @s_query
SELECT [Some_Column] FROM ##Results
WHERE RowNum BETWEEN(10-1) * 20 + 1 AND(((10 -1) * 20 + 1) + 20) - 1
答案 1 :(得分:7)
您正在构建一个字符串并将其结果放在@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';