Reputation: 844
Firstly I have a table tblSample
with ID
as column of datatype INT
. To auto generate ID for every transaction, I created a stored procedure:
DECLARE @Id INT
SELECT @Id = MAX(Id)
FROM tblSample
IF @Id IS NULL
BEGIN
SELECT 0 as Id
END
ELSE
SELECT MAX(Id) as ID FROM tblSample
Here as you observe if ID
has no rows MAX(Id)=0
then return 0 or else return MAX(ID) value so that next insertion will be greater than max(ID).
That's fine but now I had column ID
with datatype VARCHAR
I have to do similar operation how can I that?
Upvotes: 0
Views: 276
Reputation: 5656
The code looks fine so it should work with VARCHAR also but my suggestion is to use storage variable also with same datatype so it won't get conflicted anywhere in the operation:
DECLARE @Id VARCHAR(10)
Upvotes: 2
Reputation: 4192
DECLARE @Id INT
SELECT @Id=MAX(Id) FROM tblSample
IF @Id IS NULL
BEGIN
SELECT 'Your_VarCharValue' + CAST(0 AS VARCHAR) as Id
END
ELSE
SELECT 'Your_VarCharValue' + CAST(MAX(Id) AS VARCHAR) as ID FROM tblSample
Upvotes: 0