问题
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