Hi @Sudip Bhatt ,
You could not use dynamic SQL inside a user-defined function in SQL Server. Stored procedures are able to change the table data while user-defined functions are not.
But If you insist on using functions, please refer below:
Firstly, create one table and one serial number column as primary key .
create table testA
(Serialno int identity(1,1) primary key,
name varchar(1000))
DECLARE @i INT
SET @i = 1
WHILE (@i <= 300)
BEGIN
INSERT INTO testA VALUES(CONCAT('name_', @i))
SET @i = @i + 1
END
select * from testA
Secondly create the function like below:
create function NextCustomerNumber
(
@TABLE_NAME varchar(20)
)
returns varchar(1000)
as
begin
declare @column_name varchar(100)
SELECT @column_name=COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = @TABLE_NAME
declare @lastval varchar(1000)
set @lastval = 'select right(''000000000'' + convert(varchar(10),(select IsNull(max('+@column_name+'),0)+1 from '+@TABLE_NAME+')),10)'
return @lastval
end
Then we could get the statement by calling above function like below:
select dbo.NextCustomerNumber ('testa')
Output:
select right('000000000' + convert(varchar(10),(select IsNull(max(Serialno),0)+1 from testa)),10)
Finally we could run above output query and get the output as below:
Output:
0000000301
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.