且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Sql Server中添加两个Type Varchar值?

更新时间:1970-01-01 07:57:12

不要。



虽然技术上可行,但是很痛苦做,应该避免。

可以这样做:你必须自己解析每个字符串,提取数字部分和限定符(在你的例子中为GB)然后将数字转换为通过计算限定符的含义(以便3GB + 3000MB将使6GB,而不是3003GB)将数字正常化为正确数,然后再将其转换回适当的字符串秒。不好,而且非常尴尬。



相反,将您的值存储为数值,***是理性基值:例如KB。

所以你的3GB值将被存储为3 * 1024 * 1024 KB或3145728作为数字。

然后你可以轻松添加数字,并将它们格式化以便在需要时非常简单地显示。
Don't.

While it is technically possible, it's a pain to do, and should be avoided.
It can be done: you have to parse each string yourself, extract the numeric part and the "qualifier" ("GB" in your example) then convert the numeric to a number and "normalize" it to a "proper" number by working out what the qualifier means (so that 3GB + 3000MB will make 6GB, not 3003GB) then convert it back to an appropriate string again afterwards. Not nice, and very awkward.

Instead, store your value as a numeric value, preferably to a "rational" base value: KB for example.
So your 3GB value would be stored as 3 * 1024 * 1024 KB or 3145728 as a number.
You can then add numbers easily, and format them for display very simply when you need to.


OriginalGriff给你一个非常好的建议,反对这样做。如果你坚持,那么看看下面的查询,看看你必须将varchar转换为数字进行算术运算然后将它转换回varchar以便将'GB'连接到它是多么复杂:

OriginalGriff has given you a very good advice against doing it this way. If you insist, then take a look at the following query, see how complicated it is that you have to convert varchar to number for arithmetic operation then to have it converted back to varchar in order to concatenate the 'GB' to it:
update table1 set requested_space =
convert(varchar, (convert(int, substring(reverse(requested_space), 3, len(requested_space))) + 2)) +
'GB';
select * from table1



虽然它在技术上是可行的,但并不意味着我们必须这样做,当它效率不高时。


While it is technically possible, does not mean we have to do it, when it is not efficient.


我已经自己解决了.... thanx .. :) />


i have solved it by myself....thanx..:)

update UserRegistration set AllotedSpace = CAST((select SUBSTRING(AllotedSpace,0,2) from UserRegistration where ID=7) + 2 as varchar)+' GB' where ID=7