2015-09-04 49 views
0

我有這個疑問錯誤:字符串「聲明@ RepInt =」翻一番轉換無效

Dim count as integer = 4 

Dim sql As String = " DECLARE @rep INT = " + count + "; " + _ 
          " WITH cte AS " + _ 
         " (" + _ 
          " SELECT TOP (@rep) " + _ 
           " ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N " + _ 
          " FROM sys.All_Columns ac1 " + _ 
          " CROSS JOIN sys.ALL_Columns ac2 " + _ 
         ") " + _ 
         " SELECT t.Barcode" + _ 
         " FROM A_Documents t " + _ 
         " CROSS JOIN cte " + _ 
         " where idDocument = 'doc-123456' " + _ 
         " ORDER BY t.Barcode desc; " 

如果我把一個數字,沒有一個變種,IST的工作原理:

Dim sql As String = " DECLARE @rep INT = 4; " + _ 

但是,當我把我的COUNT變種,是不行的:

Dim sql As String = " DECLARE @rep INT = " + count + "; " + _ 

並出現此錯誤消息:

The conversion of string " Declare @RepInt=" to double is not valid

+1

其實你並不需要聲明變量。你可以在TOP(+ count +)內立即傳遞它。其次考慮使用參數綁定而不是字符串連接。另外如果你需要將'count'轉換爲字符串。 – lad2025

+0

再次感謝您的幫助,我不能回答您的評論,因爲不是答案 –

+1

不要緊,請在下面提出答案;) – lad2025

回答

2

這就是+運營商的預期行爲。

當您向其中提供一個數字變量時,系統會嘗試將所有其他對象轉換爲該數字類型以完成添加,因此是例外。

恕我直言,這是一個功能,因爲它可以讓你完全知道你在串接什麼。

解決方案:

Dim sql As String = " DECLARE @rep INT = " + count.ToString + "; " + _ 
2

當您嘗試添加一個字符串和一個數字,它會嘗試將字符串轉換爲數字。您可以使用&操盤手,這將東西轉換不是一個字符串轉換爲字符串:

Dim sql As String = " DECLARE @rep INT = " & count & "; " + _