SogdianWarrior
DateTime.UtcNow returns 0001-01-01T00:00:00
ALTER PROCEDURE [dbo].[GenerateCodes]
@NumOfCodes INT = 50,
@CharacterSet NVARCHAR(50) = '13456789ACDEFHKLMNPQRTVWXYZ',
@ExpirationMonths INT = 3,
@ExpirationDate DATE = NULL /* TIME FORMAT ; YYYY-MM-DD */
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Counter INT = 1;
BEGIN TRY
BEGIN TRANSACTION;
WHILE @Counter <= @NumOfCodes
BEGIN
DECLARE @RandomString VARCHAR(10);
SET @ExpirationDate = DATEADD(MONTH, 3, GETDATE());
SET @RandomString = '';
DECLARE @InnerCounter INT = 1;
WHILE @InnerCounter <= 10
BEGIN
SET @RandomString = @RandomString + SUBSTRING(@CharacterSet, (ABS(CHECKSUM(NEWID())) % LEN(@CharacterSet) + 1), 1);
SET @InnerCounter = @InnerCounter + 1;
END;
SET @UtcNow = GETUTCDATE();
INSERT INTO dbo.Codes (CODE, ExpirationDate,CreatedAt,ModifiedAt,IsActive)
VALUES (@RandomString, @ExpirationDate,@UtcNow,@UtcNow,1);
SET @Counter = @Counter + 1;
END;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT 'An error occurred. Transaction rolled back.';
PRINT ERROR_MESSAGE();
END CATCH;
END;
51 replies