如何使用SELECT和自动递增字段插入表格

时间:2014-06-18 18:09:26

标签: sql-server insert auto-increment

我正在尝试从我创建的表中插入到生产表中 - 我之前能够使用我认为导致重复的公式并且没有填充主键(在这种情况下PROSPECT_ID正确填充。)因为它是一个自动递增的字段,我正在使用另一个表中的select来插入有关如何在生产中正确自动增加此字段的任何帮助?MKT_PROSPECT

INSERT INTO MKT_PROSPECT(PROSPECT_ID,RECORD_TYPE,search_name,LABEL_NAME,FIRST_NAME,LAST_NAME,CUSTOMER_CLASS_CODE,CUSTOMER_STATUS_CODE,COMPANY_NAME,JOB_TITLE,FORMATTED_DETAIL,ADDRESS_1,ADDRESS_2,CITY,STATE,POSTAL_CODE,ADDRESS_TYPE_CODE,ADDRESS_STATUS_CODE,HOME_PHONE,EMAIL,ADDOPER) 
select PROSPECT_ID,RECORD_TYPE,SEARCH_NAME,LABEL_NAME,FIRST,LAST,CUSTOMER_CLASS_CODE,CUSTOMER_STATUS_CODE,COMPANY,TITLE,FORMATTED_DETAIL,ADDRESS1,ADDRESS2,CITY,STATE,ZIP,ADDRESS_TYPE_CODE,ADDRESS_STATUS_CODE,PHONE,EMAIL,ADDOPER from dbo.prospects  
where SEARCH_NAME IS not NULL and LABEL_NAME is not null

1 个答案:

答案 0 :(得分:0)

如果你想在John Hartsock评论中说的那样使用IDENTITY INSERT ON插入具有特定ID的表格。值得注意的是,自动增量列将继续在最大数字之上的所有其他插入(在标识插入的范围之外)。

如果您想插入并让表格自动生成,您只需在插入内容中不包含ID列:

INSERT INTO MKT_PROSPECT(RECORD_TYPE,search_name,
                         LABEL_NAME,FIRST_NAME,LAST_NAME,CUSTOMER_CLASS_CODE,
                         CUSTOMER_STATUS_CODE,COMPANY_NAME,JOB_TITLE,
                         FORMATTED_DETAIL,ADDRESS_1,
                         ADDRESS_2,CITY,STATE,POSTAL_CODE,
                         ADDRESS_TYPE_CODE,ADDRESS_STATUS_CODE,
                         HOME_PHONE,EMAIL,ADDOPER) 

             select RECORD_TYPE,SEARCH_NAME,LABEL_NAME,FIRST,LAST,
                    CUSTOMER_CLASS_CODE,CUSTOMER_STATUS_CODE,COMPANY,TITLE,
                    FORMATTED_DETAIL,ADDRESS1,ADDRESS2,CITY,STATE,ZIP,
                    ADDRESS_TYPE_CODE,ADDRESS_STATUS_CODE,
                    PHONE,EMAIL,ADDOPER from dbo.prospects  
                    where SEARCH_NAME IS not NULL and LABEL_NAME is not null