Hi,
First of all, let me say that I just don't understand a practical reason for doing this. This may cause you some problems in the future. Are you sure that you need this?
Have you considered storing your values as an auto incremented integer instead of varchar (and maybe using "0001-9999" format for display purposes only)?
Anyway, I am going to show you how this could be done.
Here's my sample:
DECLARE @Table TABLE ([Value] VARCHAR(4));
DECLARE @NewValue INT;
INSERT INTO @Table ([Value])
VALUES ('0001'), ('0009');
SET @NewValue = (SELECT ISNULL(MAX(CONVERT(INT, [Value])), 0) + 1 FROM @Table);
INSERT INTO @Table ([Value])
VALUES (REPLICATE('0', (4 - LEN(@NewValue))) + CONVERT(VARCHAR(4), @NewValue));
Note: Only numeric values should be stored in the column "Value".
Given values are '0001' and '0009'. As you can see, I am getting a new value as integer. Then I am using the
REPLICATE ( string_expression ,integer_expression ) function to repeat '0' value specified number of times.
There should be three records in the table: '0001', '0009' and newly generated
'0010'. Let's check it:
SELECT * FROM @Table;
Value
0001
0009
0010
Your stored procedure could look something like this:
USE [RealEstate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[generate]
AS
BEGIN
DECLARE @NewValue INT;
DECLARE @strGUID UNIQUEIDENTIFIER;
SET @NewValue = (SELECT ISNULL(MAX(CONVERT(INT, [RealEstateNumber])), 0) + 1 FROM [dbo].[RlRegistrationRealEstate]);
UPDATE [dbo].[RlRegistrationRealEstate]
SET [RealEstateNumber] = (REPLICATE('0', (4 - LEN(@NewValue))) + CONVERT(VARCHAR(4), @NewValue))
WHERE GUID = @strGUID;
END
By the way, you're not setting any value for @strGUID
variable!
-------------------------------------------------------------------------
Addendum:
In
SQL Server 2012 you can use the
FORMAT function instead of the
REPLICATE.
Here's the simple example:
DECLARE @NewTable TABLE ([intValue] INT);
INSERT INTO @NewTable ([intValue])
VALUES (1), (9);
SELECT FORMAT ([intValue], '0000') AS [varcharValue] FROM @NewTable;
varcharValue
0001
0009