Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Increment an ID field in sql query string

Author  Topic 

SandyK
Starting Member

9 Posts

Posted - 2006-03-03 : 16:32:28

Hello..

can anyone help me with this query string?

String SQL = "INSERT Employee(Employee ID, UserName, JobRole, Department, Level, Email)(SELECT max(EmployeeID) + 1 FROM Employee) AS Employee ID, VALUES(EmployeeID, '" + newUserName + "', '" + newJobRole + "', '" + newDept + "', '" + newLevel + "', '" + newEmail + "')";

I am trying to insert values into a table, but i have an Employee ID field, which needs incrementing. How can i do this through my SQL query string? Is this possible? As it can't accept a NULL value.

Thanks, Sandy

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2006-03-03 : 16:39:38
replace EmployeeID with
(select top 1 EmployeeID from Employee order by EmployeeID desc)

Go with the flow & have fun! Else fight the flow
Go to Top of Page

SandyK
Starting Member

9 Posts

Posted - 2006-03-03 : 16:50:09
hmm, i tried it...

String SQL = "INSERT Employee(Employee ID, UserName, JobRole, Department, Level, Email) VALUES((SELECT TOP 1 EmployeeID FROM Employee ORDER BY EmployeeID desc),'" + newUserName + "', '" + newJobRole + "', '" + newDept + "', '" + newLevel + "', '" + newEmail + "')";

Got an error in syntax near the ID and the ORDER BY is what i got.

???? Thanks
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2006-03-03 : 17:02:35
Insert with VALUES only allows scalar values, not subqueries.

Do your Insert in this form:

insert into Mytable (col1, col2, etc.)
select col1, col2, ...



CODO ERGO SUM
Go to Top of Page

SandyK
Starting Member

9 Posts

Posted - 2006-03-03 : 17:46:17
Ok..

so i changed the field in my db to be an IDENTITY field, so it automatically increments... and that sorted it... doh!
thanks to those who replied! :)
Go to Top of Page
   

- Advertisement -