Click here to Skip to main content
15,901,426 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello

I want a procedure or function in sql server by which i will send table name and one field of the table which is an increment number and it will return me max number of that field which i will put in a variable and return the max number.




Thanks....
Posted

Something like this:

SQL
DECLARE @TableName NVARCHAR(100)
DECLARE @FieldName NVARCHAR(100)

DECLARE @Query NVARCHAR(MAX)

SET @Query = 'SELECT MAX(' + @FieldName + ') FROM ' + @TableName
EXEC(@Query)
 
Share this answer
 
Comments
Jimut123456789 27-Aug-12 8:50am    
But can I put the value in a variable.
When you insert data into a table, the server can generate that value for you - do not try it yourself, as you might face concurrency problems (two users adding data with the same new id value).
I the table definition, use an integer with the "identity" property switched on ("Is Identity", "Yes").
When you need to know that value on your clent after inserting into the database, do a SELECT @@ID.
 
Share this answer
 
use below Query,
SQL
select isnull(max(AutoIncrFldNm),0) + 1 from tblnm


In store-procedure if you are passing tablename & fieldname dynamically
then,
SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Sp_ReturnNextAutoId
	@tblNm as varchar(50),
    @fldNm as varchar(50)
AS
BEGIN
	DECLARE @execquery AS NVARCHAR(MAX)
	SET @execquery = 'select isnull(max(' + QUOTENAME(@fldNm) + '),0) + 1 from ' + QUOTENAME(@tblNm)
	execute(@execquery)
END
GO

--tocheck sp
--exec Sp_ReturnNextAutoId 'tbl1','fld1'


Happy Coding!
:)
 
Share this answer
 
SQL
Create proc sp_increment
(@TableName NVARCHAR(100),
@ColumnName NVARCHAR(100)
) AS
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT Isnull(MAX(' + @ColumnName + '),0)+1 FROM ' + @TableName
print @sql
EXECUTE sp_executesql  @sql



When i have no data in my table, it will return me 1

If i have exisitng data, then it will return me max+1

SQL
sp_increment 'tbl_user' ,'userid'
 
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