2017-06-05 26 views
1

我在我的數據庫表中有這一列及其字符串。我沒有做這個表,我不能改變數據類型。SQL將列轉換爲浮動在where子句中

但是我需要將它轉換爲我的where子句中的float,以便我可以將它與浮點數進行比較。

我已經試過了鑄造我的專欄,爲float:

sql += " AND CAST (ec.bedrooms as float) <= " + id.beds.Max().Split('-')[1] + " AND CAST (ec.bedrooms as float) >= " + id.beds.Min().Split('-')[0]; 

,但沒有工作,因爲我得到這個錯誤:

An error occurred while reading from the store provider's data reader. See the inner exception for details 

我在做什麼錯?

這裏是正在爲部分

AND CAST (ec.bedrooms as float) <= 3 AND CAST (ec.bedrooms as float) >= 2 

"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error converting data type nvarchar to float.","ExceptionType":"System.Data.SqlClient.SqlException","StackTrace":" at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)\r\n at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)\r\n at System.Data.SqlClient.SqlDataReader.Read()\r\n at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.StoreRead()"}} 
+3

請出示*實際*生成的查詢。 – Siyual

+0

和堆棧跟蹤 – hardkoded

+4

您應該真正使用參數來構建SQL查詢。 –

回答

0

看起來你ec.bedrooms產生什麼是具有非數字值......您可以檢查象下面這樣:

sql += " AND CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) <= " + id.beds.Max().Split('-')[1] + " AND 
CAST (iif(isnumeric(ec.bedrooms)>0,ec.bedrooms,null) as float) >= " + id.beds.Min().Split('-')[0];