MS SQL Server: cast double to string and compare text

自作多情 提交于 2019-12-24 15:53:51

问题


In MS SQL Server I have a filed of type double that is called ID, and that stores ID numbers, surprisingly enough. Anyway, I want to be able to search ID numberss like text - say I want all ID's that starts with 021 or that ends with 04 - to do so I need to convert the double the string.

My problem is that ID numbers here are 9 digits, so when I try SELECT str([id]) I get something like 02123+e23, which is not good for my purpose.

How do I go about converting it to a string that looks exactly the same, and can be compared against other strings?

EDIT: I tried SELECT str([id],9,0) and I got the right string, or at least what looked right to me, but when comparing against equal strings the comparison failed. Any ideas why?

Thanks!


回答1:


If your ID's are stored as numbers, then there will not be prefixed zeros, so finding all records that starts with '021' really means finding those that starts with '21'

SELECT * FROM MyTable
WHERE CAST(Id AS VARCHAR) LIKE '21%'



回答2:


You can use the convert method in TSQL, and sepcify the precision : http://msdn.microsoft.com/en-us/library/ms187928.aspx (float and real Styles section in the Remarks).

But why can't you convert your string into double to make the comparison ?




回答3:


SELECT * FROM tablename WHERE SUBSTRING(CAST(id AS VARCHAR), 0, 9) = '123456789'



来源:https://stackoverflow.com/questions/19153884/ms-sql-server-cast-double-to-string-and-compare-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!