Question

I have an asp.net application that uses SQL Server 2005. In this application I want to create a function that returns unique reference numbers for new Inquiry Id.

I read about UNIQUEIDENTIFIER but it has a specific format like 1548C3E02-2D73-4244-8787-D45AC590519A.

I want output like 1703-HJIF-2012. Here first have combination of current datepart like date and month, second is random string which auto generate and third one is year part of current date. I don't have any idea how I could create such a function and how I would be calling this function from a stored procedure and get result string from function with this required format.

here some one posted me this function but this generates spaces instead of 0 :

create function UniqueRefNum (@r1 float, @r2 float, @r3 float, @r4 float)
returns char(14)
begin
    -- Not sure if rand() might return 1.0
    -- If it does, the conversion code below would produce a character that's not an
    -- uppercase letter so let's avoid it just in case
    if @r1 = 1.0 set @r1 = 0
    if @r2 = 1.0 set @r2 = 0
    if @r3 = 1.0 set @r3 = 0
    if @r4 = 1.0 set @r4 = 0

    declare @now datetime
    set @now = getdate() -- or getutcdate()

    declare @m char(2)
    if month(@now) < 10
        set @m = '0' + month(@now)
    else
        set @m = month(@now)

    declare @d char(2)
    if day(@now) < 10
        set @d = '0' + day(@now)
    else
        set @d = day(@now)

    return @m + @d + '-' + 
           char(65 + cast(@r1 * 26 as int)) + 
           char(65 + cast(@r2 * 26 as int)) + 
           char(65 + cast(@r3 * 26 as int)) + 
           char(65 + cast(@r4 * 26 as int)) + 
           '-' + cast(year(@now) as varchar)
end

You then call the function from your stored procedure like this:

declare @uniqueRef char(14)
set @uniqueRef = dbo.UniqueRefNum(rand(), rand(), rand(), rand())

---------------Updated-----------------------------

it's generates out put is like that :

4 24-HHBH-2014

and i want output something like this :

2404-HHBH-2014
DDMM-XXXX-YYYY
Was it helpful?

Solution

You need to cast the day/month values to char before concatenating the strings.

declare @m char(2)
if month(@now) < 10
    set @m = '0' + cast(month(@now) as char(1))
else
    set @m = month(@now)

declare @d char(2)
if day(@now) < 10
    set @d = '0' + cast(day(@now) as char(1))
else
    set @d = day(@now)

The thing is that the string in '0' + month(@now) is converted to integer and then the two numbers are added up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top