Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使用insert语句将ID从一个表分配到另一个表中_Sql_Sql Server 2008 - Fatal编程技术网

Sql 使用insert语句将ID从一个表分配到另一个表中

Sql 使用insert语句将ID从一个表分配到另一个表中,sql,sql-server-2008,Sql,Sql Server 2008,我一直在尝试将数据从临时表中的一行插入到数据库中的现有表中,我已经设法做到了这一点,但我还想增加主题表中已经存在的ID列。临时表有两列,ID和keyword,但是我从临时表中得到的关键字总是第一行,因此临时表中的ID总是1,而我希望ID是主题表的计数加1 对不起,如果以前有人问过这个问题,我只是不知道要搜索什么 这就是我到目前为止的情况,不确定我是否在正确的轨道上: --declare topic id and set it as one more than the current numbe

我一直在尝试将数据从临时表中的一行插入到数据库中的现有表中,我已经设法做到了这一点,但我还想增加主题表中已经存在的ID列。临时表有两列,ID和keyword,但是我从临时表中得到的关键字总是第一行,因此临时表中的ID总是1,而我希望ID是主题表的计数加1

对不起,如果以前有人问过这个问题,我只是不知道要搜索什么

这就是我到目前为止的情况,不确定我是否在正确的轨道上:

 --declare topic id and set it as one more than the current number of rows
 DECLARE @T_ID int
 SET @T_ID = (SELECT COUNT(*) FROM Topic)+1

 --insert keyword into Topic table
 INSERT INTO Topic(Topic_ID, Topic_Name)
 SELECT keyword FROM #tempKeywords 
 WHERE ID = 1
COUNT(*)
更改为
MAX(Topic\u ID)
,但最好将
Topic\u ID
声明为标识列,让SQLServer处理增量

SET @T_ID = (SELECT ISNULL(MAX(Topic_ID),0)+1 FROM Topic)

 --insert keyword into Topic table
 INSERT INTO Topic(Topic_ID, Topic_Name)
 SELECT @T_ID, keyword FROM #tempKeywords 
 WHERE ID = 1
如果将Topic_ID列更改为Identity,则

 --insert keyword into Topic table
 INSERT INTO Topic(Topic_Name)
 SELECT keyword FROM #tempKeywords 
 WHERE ID = 1