2015-01-15 91 views
1

當我嘗試背後叫我的存儲過程的代碼的形式在我的網站,我得到這個錯誤。我一直停留相當長的一段時間了,因爲我不知道的任何地方我轉換或聲明的值作爲整數做。這是我的SQL語句:錯誤轉換nvarchar的數據類型爲int

create procedure GetRepPhoneID 
@Rep  nvarchar(100), 
@phoneID nvarchar(100) output 
as 
set @phoneID = (select concat(CustomerRepPh, '~', cast(RepID as nvarchar(100))) as 'PhoneAndID' 
from Reps 
where [email protected]) 
return @phoneID 
go 
從我的C#代碼

那麼後面我試圖調用存儲過程:

公共靜態字符串GetRepPhone(字符串衆議員) { 字符串連接= WebConfigurationManager.ConnectionStrings [ 「JDC_DatabaseConnectionString」]的ConnectionString。 的SqlConnection的SqlConnection =新的SqlConnection(連接);

//This funciton will take all of the values and create them. 
    try 
    { 
     sqlConnection.Open(); 
    } 
    catch (Exception err) 
    { 
     Console.WriteLine(err.Message); 
    } 

    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = sqlConnection; 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandText = "GetRepPhoneID";   //getting the procedure created in SQL. 

    SqlParameter CustomerParam = new SqlParameter(); 
    CustomerParam.ParameterName = "Rep"; 
    CustomerParam.SqlDbType = SqlDbType.NVarChar; 
    CustomerParam.Value = Rep; 
    CustomerParam.Direction = ParameterDirection.Input; 

    //We are using an output parameter not a return one because it is a string. 
    SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100); 
    ReturnParam.Direction = ParameterDirection.Output; 

    cmd.Parameters.Add(CustomerParam); 
    cmd.Parameters.Add(ReturnParam); 

    cmd.ExecuteNonQuery(); 

    sqlConnection.Close(); 
    return ReturnParam.Value.ToString(); 
} 

我做同樣的事情多次在我的代碼,但他們都返回整數所以一直沒有異常,所以我知道它應該工作的錯誤。錯誤正在cmd.ExecuteNonQuery()行中引發。確切的錯誤是:

Conversion failed when converting the nvarchar value '(111)222-6666~29' to data type int. 

我明白,我不能說字符串轉換爲整數,但我不認爲在我的代碼的任何地方,我宣佈一個整數,或者我試圖轉換。

任何幫助將不勝感激。謝謝。

回答

3

你是一個OUTPUT參數混淆一個RETURN值。 RETURN是類型INT的可選狀態碼。將另一個參數聲明爲OUTPUT。

意義,這是在存儲過程中無效:

return @phoneID 

相反,加@phoneID nvarchar(100) OUTPUT參數列表並刪除DECLARE @PhoneID

CREATE PROCEDURE GetRepPhoneID 
(
    @Rep  NVARCHAR(100), 
    @phoneID NVARCHAR(100) OUTPUT 
) 
AS 
SET NOCOUNT ON; 

SELECT @phoneID = concat(CustomerRepPh, '~', RepID) 
FROM Reps 
WHERE CustomerRep = @Rep; 

上述表示整個 PROC。你不需要RETURNSET

然後在C#代碼,您需要更改參數是如何規定:

SqlParameter ReturnParam = new SqlParameter("phoneID", SqlDbType.NVarChar, 100); 
ReturnParam.Direction = ParameterDirection.Output; 

然後刪除此行,因爲它沒有必要的,因爲該參數的值將保持連接關閉後:

string PhoneAndID = cmd.Parameters[1].Value.ToString(); 

並更改return是:

return ReturnParam.Value.ToString(); 

拉斯維加斯您可能需要更新輸入參數的聲明,如下所示:

SqlParameter CustomerParam = new SqlParameter("Rep", SqlDbType.NVarChar, 100); 
CustomerParam.Value = Rep; 
CustomerParam.Direction = ParameterDirection.Input; 
+0

感謝您的幫助。這擺脫了原來的錯誤,但現在是拋出'字符串[1]:Size屬性有0.' – 2015-01-15 17:20:37

+0

@ChaseErnst我剛纔編輯與帕拉姆聲明C#部分的大小無效。 – 2015-01-15 17:23:22

+0

這使我回到原來的錯誤。我已將問題更新到我當前的代碼。 – 2015-01-15 17:26:58

相關問題