Click here to Skip to main content
15,895,606 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
In database design as follows (table name company)
Fieldname Data Type
Compid (primary key) char(10)

In database record as follows (table name company)
Compid
1
2
3
4
5

i want to get max value of compid in company table.
for that how can i do using sql server.
Posted
Comments
PIEBALDconsult 20-Aug-15 11:44am    
You really don't want to do MAX(Compid), you just don't. Use a proper ID and the correct techniques for working therewith.
Sergey Alexandrovich Kryukov 20-Aug-15 11:51am    
Of you want arithmetic maximum based on numeric comparison, use numeric data type, not varchar.
—SA

Correct me if I'm wrong but there seems to be some fundamental problems in your approach.

  • First of all, why do you use a character data type for numeric values?
    Always choose the data type based on the true underlying value type. In this case you'd probably want to use int or bigint.
  • Don't create unique values by yourself, let the database do the job for you. Searching for the maximum value and based on that generating a new key value requires additional and unnecessary roundtrips to the database which takes time. You have multiple choices for the key generation in the database:

    • uas e numeric data type and let the IDENTITY[^] definition to create new values for you
    • Use uniqueidentifier and define a NEWID[^] as the default value
    • Use a sequence[^] to generate new, unique values

 
Share this answer
 
Comments
Maciej Los 20-Aug-15 17:15pm    
Short and to the point. +5!
Wendelius 20-Aug-15 23:45pm    
Thanks Maciej.
To get max you use the MAX function as PIEBaLDconsult says, but there is a good chance you are doing something wrong if you are doing this.

However,
SQL
SELECT MAX(Compid) AS MaxCompId FROM table
 
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