2014-01-23 149 views
1

我試圖從我的數據庫中返回一個字符串值,但是查詢返回「0」,儘管SELECT查詢的目標是一個nvarchar列。 查詢有效且正確運行,當使用SQL-SMS運行時返回「KYO」。對Nvarchar列的返回SELECT查詢

這是方法,因爲預計在我使用它的其他地方,其工作的,我使用的返回數據:

public static object GetData(string sql, SqlParameter[] parameters) 
    { 
     try 
     { 
      using (DbConnection connection = factory.CreateConnection()) 
      { 
       connection.ConnectionString = connectionString; 

       using (DbCommand command = factory.CreateCommand()) 
       { 
        command.Connection = connection; 
        command.CommandType = CommandType.Text; 
        command.CommandText = sql; 

        if (parameters != null) 
        { 
         foreach (var parameter in parameters) 
         { 
          if (parameter != null) 
           command.Parameters.Add(parameter); 
         } 
        } 

        object result = null; 
        SqlParameter returnValue = new SqlParameter("ReturnValue", result); 
        returnValue.Direction = ParameterDirection.ReturnValue; 
        command.Parameters.Add(returnValue); 

        connection.Open(); 
        command.ExecuteScalar(); 
        result = command.Parameters["ReturnValue"].Value; 
        return result; 
       } 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 
} 

這是拋出一個轉換異常,因爲它是返回一個int的方法而不是字符串:

private static String GetManufacturerCode(Int32 manufacturerID) 
    { 
     try 
     { 
      StringBuilder sql = new StringBuilder(); 
      sql.Append("SELECT ManufacturerCode FROM Manufacturers WHERE ManufacturerID = @ID"); 

      SqlParameter id = new SqlParameter("@ID", manufacturerID); 

      return(String)DB.GetData(sql.ToString(), new[] { id }); 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
    } 

我還設置returnValue.DbType = DbType.String;作爲測試,這仍然返回一個整數。

的,我成功地使用GetData(...)方法的一個例子是:

public static Int32 GetMonitoredCount() 
    { 
     try 
     { 
      String GetMonitoredCount = "SELECT COUNT(*) FROM Devices WHERE Monitored = 1 "; 

      return (Int32)DB.GetData(GetMonitoredCount, null); 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 

我認爲它可能會返回一個布爾位,但作爲我的查詢執行正確我會假設它會返回1不爲0。

爲什麼要返回一個整數?我怎樣才能使用我的模式返回一個字符串?

回答

4

ReturnValue始終返回int - 這是設計。

而是這整個區塊的

object result = null; 
SqlParameter returnValue = new SqlParameter("ReturnValue", result); 
returnValue.Direction = ParameterDirection.ReturnValue; 
command.Parameters.Add(returnValue); 

connection.Open(); 
command.ExecuteScalar(); 
result = command.Parameters["ReturnValue"].Value; 

嘗試

connection.Open(); 
object result = command.ExecuteScalar(); 

這將返回您的SQL語句

方法ExecuteScalar本身能夠返回值的實際結果 - 它首先返回結果集第一行的列,當您的查詢返回單個值時是理想的。