2012-06-22 34 views
0

我在处理类型转换的麻烦......问题与类型的转换

CODE:

public static string isLocalIncidentSubmitted() 
{ 

    string query = "SELECT Submit From [MVCOmar].[dbo].PrideMVCSubmitLog WHERE [email protected]"; 

    DataTable dt = new DataTable(); 
    SqlConnection connection = new SqlConnection(connectionStr4); 

    SqlCommand command = new SqlCommand(query, connection); 
    command.Parameters.AddWithValue("@existingNum", MyGlobals1.secondversionDisplayTesting); 

    connection.Open(); 
    SqlDataAdapter adp = new SqlDataAdapter(command); 
    adp.Fill(dt); 
    connection.Close(); 
    command.Dispose(); 
    connection.Dispose(); 


     return dt.Rows[0]["Submit"].ToString(); 

} 

表提交的类型为varchar的

我得到一个大错误但这里是它的前几行:

 
System.Data.SqlClient.SqlException: Conversion failed when converting from a character string to uniqueidentifier. 
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) 
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) 
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) 
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) 
at System.Data.SqlClient.SqlDataReader.HasMoreRows() 
+1

如果你要问一个关于类型转换的问题,如果您提供有关所涉及类型的更多详细信息,它将非常有帮助...... –

+0

ReportID只能包含36个字符串。 existingNum的长度也是36个字母,所以问题在于提交 – Bulvak

+0

secondversionDisplayTesting是string类型,Submit列的类型是varchar,最大字符串长度是5. – Bulvak

回答

3

它看起来s就像你的ReportID是SQL中的Guiduniqueidentifier,但你试图给它一个字符串值。你确定你在查询中使用了正确的字段吗?

如果您MyGlobals1.secondversionDisplayTesting是一个字符串,然后做这样:

Guid g = Guid.Parse(MyGlobals1.secondversionDisplayTesting); 
command.Parameters.AddWithValue("@existingNum", g); 
+0

ReportID是一个唯一标识符和我传递的值,existingNum是一个字符串...如果不是字符串什么,我必须通过existingNum作为? ReportID是uniqueidentifier类型,但我不知道如何将C#字符串转换为唯一标识符@Coding Gorilla – Bulvak

+1

@Nadal http://msdn.microsoft.com/en-us/library/system.guid.parse.aspx – asawyer

+0

@Nadal See我的更新 – CodingGorilla

0

貌似问题不在于你是返回什么,但SQL您要执行。将try/catch中的return语句全部包裹起来,我相信你会发现对此的确认。你的SQL是你的问题所在。

从MSDN(http://msdn.microsoft.com/en-us/library/ms187942.aspx):将唯一标识符 类型被认为是一种字符类型的目的从一个字符表达式转换 ,因此受制于 转换为字符类型的截断规则。也就是说,当 字符表达式被转换为 不同大小的字符数据类型时,对于新数据类型太长的值将被截断 。请参阅示例部分。

示例以下示例将uniqueidentifier值转换为char数据类型 。

DECLARE @myid uniqueidentifier = NEWID(); 
SELECT CONVERT(char(255), @myid) AS 'char'; 
0

尝试使用,而不是.AddWithValue .Add,使您可以指定参数的类型和大小,像这样:

command.Parameters.Add("@existingNum", SqlDbType.UniqueIdentifier).Value = MyGlobals1.secondversionDisplayTesting;