如何附加到 SQL 中的现有记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6312692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:56:29  来源:igfitidea点击:

How to append to a existing record in SQL?

sqldatabasetsqlsql-server-2008

提问by jorame

Can someone tell me how to append in SQL? I've going around all day trying to figure this out. This is what I have so far:

有人能告诉我如何在 SQL 中追加吗?我整天都在试图弄清楚这一点。这是我到目前为止:

update table1 
set field1 = field1 + '123456' 
where field2 = '12'

Sorry, I forgot to mention that I'm updating more than one field in the statement.

抱歉,我忘了提及我正在更新声明中的多个字段。

回答by bsexton

Your statement should work as long as field1 is not null or the data to be appended is not null.

只要 field1 不为空或要附加的数据不为空,您的语句就应该起作用。

Something like this could help in the case where field1 is null.

在 field1 为空的情况下,这样的事情可能会有所帮助。

update table1 set field1 = ISNULL(field1, '') + '123456' where field2 = '12'

回答by Randy

in Oracle, the string concatenation goes like this:

在 Oracle 中,字符串连接是这样的:

field1 = field1 || '12345'

回答by Wes

Your question is a bit confusing because you are saying append but your example is really just a set operation:

您的问题有点令人困惑,因为您说的是 append 但您的示例实际上只是一个集合操作:

update table1 set field1 = '123456', field2 = '' where field2 = '12'

if you were actually appending it would depend on your database but lookup string concatenation for reference.

如果您实际上是追加,则取决于您的数据库,但查找字符串连接以供参考。

update table set field1 = concat(field2, '3456') where field2 = '12'

回答by MikeM

here are the differences between varchar concatenation and integer addition, you appear to have varchar concatenation going on, you may need to use CAST and CONVERT (Transact-SQL)to add your numbers

这是 varchar 连接和整数加法之间的区别,您似乎正在进行 varchar 连接,您可能需要使用CAST 和 CONVERT (Transact-SQL)来添加您的数字

example 1 w/integers:

示例 1 带整数:

DECLARE @table1 TABLE(field1 int, field2 int)
INSERT INTO @table1 VALUES (123456, 12)
SELECT 'before' as 'before', * FROM @table1

UPDATE @table1 SET field1 = field1 + 123456 WHERE field2 = 12
SELECT 'after' as 'after', * FROM @table1

example 1 results:

示例 1 结果:

int addition

此外

example 2 w/varchar:

带有 varchar 的示例 2:

DECLARE @table2 TABLE(field1 varchar(50), field2 varchar(2))
INSERT INTO @table2 VALUES ('123456', '12')
SELECT 'before' as 'before', * FROM @table2

UPDATE @table2 SET field1 = field1 + '123456' WHERE field2 = '12'
SELECT 'after' as 'after', * FROM @table2

example 2 results:

示例 2 结果:

varchar concat

varchar 连接

回答by Abdulkadir Suleiman

If you are working with MySQL the query can be simplified as

如果您正在使用 MySQL,则查询可以简化为

UPDATE table set field1 = CONCAT('123456', field1) where field2 = '12'