Convert from string with leading zeros to bigint in SQL Server CE isn't working

扶醉桌前 提交于 2019-12-11 03:15:46

问题


I have a SQL Server Compact (3.5) database with a nvarchar column with lots of data that looks like 000000000011070876. I'm trying to copy that data to another column that is a BIGINT, using the CONVERT function.

My first try was:

UPDATE Mobile_Reservation 
SET SAPNo = CONVERT(BIGINT, ItemNumber)

If I run this query in SQL Server 2008 R2, it works fine. 000000000011070876 becomes 11070876. Unfortunately, in SQL Server CE, it becomes 0. Apparently it cannot handle the leading zeros. But it will turn 000000004000010576 into 40, which I assumed meant it was only looking at the first 10 digits. Then I tried:

UPDATE Mobile_Reservation 
SET SAPNo = CONVERT(BIGINT, SUBSTRING(ItemNumber, 8, 10))

With a start index of 8, I assumed it would start just before the 4 (The first 8 digits are always 0s, but may be more than 8 0s). This worked somewhat better, but not successfully. 000000000011070876 became 1107 and 000000004000010576 became 40000105.

Then I tried the hardcoded string:

UPDATE Mobile_Reservation 
SET SAPNo = CONVERT(BIGINT, '4000010576')

And this worked fine, which confused me even more. I tried a few different combinations of strings, and the logic it seems to use is: for every leading 0 in the string, a char from the other end is removed. '1234' becomes 1234, but '01234' becomes 123. But it's not a hard fast rule, because 04000010576 becomes 40000105, which means the single leading 0 is removing two digits from the end...

Is this a problem with SQL Server CE's implementation of CONVERT, or perhaps something else I'm not noticing? Any thoughts on how to fix this?


回答1:


I wound up solving this problem with:

UPDATE Mobile_Reservation 
SET SAPNo = CONVERT(BIGINT, REPLACE(LTRIM(REPLACE(ItemNumber, '0', ' ')), ' ', '0')) 

Not the nicest solution, but it works.




回答2:


There is an implicit conversion between bigint and nvarchar() -- what about just trying

UPDATE Mobile_Reservation SET SAPNo = ItemNumber

If not that, then sometimes you also can get away with something like

UPDATE Mobile_Reservation SET SAPNo = 0 + ItemNumber

I'm sorry I don't have SQL CE to test on.



来源:https://stackoverflow.com/questions/26745902/convert-from-string-with-leading-zeros-to-bigint-in-sql-server-ce-isnt-working

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