简体   繁体   English

SQL插入表。 值=(插入前的值)+一个数字(例如1000)

[英]SQL insert into table. have value = (value before inserted) + a number(ex 1000)

New to SQL. SQL新手。 I am doing an insert into, where i want to copy all my existing daya, but in the id field, add 1000 to the id. 我正在插入,要复制所有现有的daya,但在id字段中,将1000添加到id。 Ex, if the old id was 1, i want the new id to be 1001. 例如,如果旧ID为1,我希望新ID为1001。

TABLE EXAMPLE of what i would like the output to be 我想要输出的表示例

id      fname    lname
1       tina     smith
2       mark     brown
3       lucy     cox
1001    tina     smith
1002    mark     brown
1003    lucy     cox

i know the insert statement would be similar to this below. 我知道插入语句将类似于以下内容。 just cant figure out how to set up the id in that select query. 只是无法弄清楚如何在该选择查询中设置ID。 Would you put something like (id +1000), or is there some other way to add a value? 您会输入(id +1000)还是添加值的其他方法?

insert into tablenamehere
(id, fname, lname)
select
(id, fname, lname)
from tablenamehere

I would expect the results to be the value 1000 added to my original id numbers. 我希望结果是将值1000添加到我的原始ID编号中。 As shown in the table above. 如上表所示。 So if my ID was 1, there would now be a new ID 1001 with the same first and last name as 1. 因此,如果我的ID为1,那么现在将有一个新ID 1001,其名字和姓氏与1相同。

INSERT INTO mytable (id, fname, lname)
    SELECT id + 1000, fname, lname
    FROM mytable;

That's it. 而已。

EDIT: Seems like Islingre beat me to it. 编辑:似乎像伊斯林格(Islingre)击败了我。 But as (s)he says, remember to turn off IDENTITY, or it will throw an error. 但是正如他所说,请记住关闭身份,否则将引发错误。

  INSERT INTO Categories (CategoryID, CategoryName, Description, Picture)
  SELECT (CategoryID + 1000), CategoryName, Description, Picture FROM Categories

Just tested this on a Northwind DB, and it works perfect: 刚刚在Northwind数据库上进行了测试,它可以完美运行:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM