I’ve been trying to insert data from one row in a temporary table into an existing table in my database, which I’ve managed to do, but I also want to increment the ID column that already exists in the Topic table. The temp table has two columns, ID and keyword, but the keyword I’m getting from the temp table is always the first row, so the ID will always be 1 in the temp table, whereas I want the ID to be the count of the topic table plus 1.
Sorry if this has been asked before, I just had no idea what to search for!
This is what I have so far, not sure if I’m on the right track or not:
--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
Change the
COUNT(*)toMAX(Topic_ID)but it would be better if you had declaredTopic_IDas Identity column letting SQLServer handles the incrementIf you change Topic_ID column to Identity, then you’ll have