Click here to Skip to main content
15,888,802 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Insert into sql with declared value max number value in column

What I have tried:

In update string working fine

string saveStaff = "declare @maxNo integer = 0 select @maxNo = isnull(max(redni_broj), 0) from dbo.drzave INSERT into dbo.drzave (redni_broj, Ime, Valuta, Poziv_na_broj, A2, A3, Num) VALUES ('@maxNo+1',@Ime,@Valuta,@Poziv_na_broj,@A2,@A3,@Num)";
Posted
Updated 2-Apr-18 9:05am
Comments
Goran Bibic 2-Apr-18 15:05pm    
string saveStaff = "declare @maxNo integer = 0 select @maxNo = isnull(max(redni_broj), 0) from[dbo].[drzave] ; Set @maxNo=@maxNo+1; INSERT into [dbo].[drzave] (redni_broj) VALUES (@maxNo)";

Instead of trying to figure out what is the maximum value in a column I would suggest using an autonumbered field, for example IDENTITY (Property) (Transact-SQL) | Microsoft Docs[^]

Using such field the database automatically assigns new value without any additional client side logic. Just remember to define the column as primary key to enforce uniqueness.
 
Share this answer
 
v2
Comments
[no name] 2-Apr-18 13:39pm    
I prefer sequences. Some more work, but much more freedom :-)
Wendelius 2-Apr-18 13:44pm    
Yep, I know. I personally prefer GUID's because of various reasons, replication for example, but in this case I think identity is a good starting point.
Goran Bibic 2-Apr-18 13:47pm    
Solution for me?
Maciej Los 2-Apr-18 13:50pm    
This is solution for you, Goran!
Wendelius 2-Apr-18 14:03pm    
If you don't use replication and do not have any other special requirements, IDENTITY is a very easy solution.
string saveStaff = "declare @maxNo integer = 0 select @maxNo = isnull(max(redni_broj), 0) from[dbo].[drzave] ; Set @maxNo=@maxNo+1; INSERT into [dbo].[drzave] (redni_broj) VALUES (@maxNo)";
 
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