Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello to everyone.
I have a problem, I am copying data from one table to another table and i want one of my column value should be start from 1 and incremented in every row inserted in copying table.
i have use identity property on another column so i can't use it again.
I am using subquery.
This is my code:

SQL
insert into tbExaminer (iStudentId_FK, iSubjectId_FK, iTokenID_FK,/*this column should be auto incr ->>>*/ iQno_FK, sQuestion, sAns1, sAns2, sAns3, sAns4, iRightAns, iMarks, sType, dOnDated, iResponse)
select 1, 1, 1, 'what to do here to get incr value', sQuestion, sAns1, sAns2, sAns3, sAns4, iRightAns, iMarks, sType, CONVERT(VARCHAR(10), GETDATE(), 105), 0 from tbQuestionBank
where iSubjectIdFK = 1


Here value of iQno_FK column i want to incremented value..
please help to sort this..
Thanks in advance
Posted
Updated 4-May-14 20:46pm
v2
Comments
www-sahilv 5-May-14 4:08am    
Thaks to all to provide their valuable responses.

You can use identity column any time, there is no issue in that. Only do not make it primary key if it primary key already there in your table

create table #tblStudent
(
    ID int primary key identity(1,1),
    Number UNIQUEIDENTIFIER DEFAULT NEWID(),
    Name nvarchar(50)
)
 
Share this answer
 
v2
Comments
www-sahilv 5-May-14 4:02am    
I tried but i got the warning that only one identity column allowed in table.
Try this.


SQL
insert into tbExaminer (iStudentId_FK, iSubjectId_FK, iTokenID_FK,/*this column should be auto incr ->>>*/ iQno_FK, sQuestion, sAns1, sAns2, sAns3, sAns4, iRightAns, iMarks, sType, dOnDated, iResponse)
select 1, 1, 1, ROW_NUMBER() OVER(ORDER BY GETDATE()), sQuestion, sAns1, sAns2, sAns3, sAns4, iRightAns, iMarks, sType, CONVERT(VARCHAR(10), GETDATE(), 105), 0 from tbQuestionBank
where iSubjectIdFK = 1
 
Share this answer
 
Comments
www-sahilv 5-May-14 4:01am    
Thanks Syed Asif Iqbal Sir, This is exactly what i was looking for.
Thanks a lot.
If it a bulk insert you can use ROW_NUMBER[^] function in your select statement to get a running number...
For single insert you may use a sub-query like (select max(iQno_FK) + 1 from [table]) as the value...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900