2014-02-20 120 views
7

我不知道如何解決這個錯誤:轉換失敗2008

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('[email protected]+'-1) * '[email protected]+' + 1 
AND((('[email protected]+' -1) * '[email protected]+' + 1) + '[email protected]+') - 1'; 
+3

cast @ PageIndex1 to varchar,因爲您要填充字符串s_query –

回答

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) * '[email protected]+' + 1 
AND((('[email protected]+' -1) * '[email protected]+' + 1) + '[email protected]+') - 1'; 
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