如何在Sql Server中添加两个Type Varchar值? [英] How Do I Add Two Values Of Type Varchar In Sql Server?

查看:118
本文介绍了如何在Sql Server中添加两个Type Varchar值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格名称SpaceRequest显示在下面



ID(数字)名称(varchar)Requested_Space(varchar)状态




1 Pranav 1GB True



i想要更新值Requested_Space。

即2GB + 1GB应该总共3GB ...通过查询

我怎么做?

帮助.. :)

thanx提前

I have one table name SpaceRequest showing below

ID(numeric) Name(varchar) Requested_Space(varchar) Status


1 Pranav 1GB True

i want to update values to the column Requested_Space.
i.e 2GB + 1GB should make 3GB in all...through query
how i can do it??
HELP..:)
thanx in advance

推荐答案

不要。



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

可以这样做:你必须自己解析每个字符串,提取数字部分和限定符(在你的例子中为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


这篇关于如何在Sql Server中添加两个Type Varchar值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆