Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help on Creating a function

Author  Topic 

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2010-07-11 : 03:32:20
Hi Gurus,

I have created a function basically to return an unique ID for a table.
The ID is is atored in a table IdMaster.

quote:
CREATE FUNCTION [dbo].[GetId] (@Today Datetime)
RETURNS nchar(8)
with execute as caller
AS
BEGIN
declare @seqno nchar(8);
declare @No nchar(4);
select @seqno = year(@today);
select @No=cast(cast(right(LastId, 4)as int)+1 as nchar(4)) from Idmaster;
select @No=left(replicate('0', 4), 4-len(@No));
RETURN (@seqno + @No);
END


When I call the function

quote:
SELECT DBO.GETID(GETDATE())

It returns 2010 where as it should be 20100002

Thanks

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2010-07-11 : 03:54:37
please provide sample of IDMaster Table.
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2010-07-11 : 03:57:39
declare @seqno nchar(4);
...
select @No=left(replicate('0', 4), 4-len(@No)) + @No ;
Go to Top of Page

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2010-07-11 : 04:04:50
try this. i've added 2 extra variables to make you the whole process clearer.


CREATE FUNCTION [dbo].[GetId] (@Today Datetime)
RETURNS char(20)
with execute as caller
AS
BEGIN
declare @seqno char(4);
declare @seqno2 char(20);
declare @No char(4);
declare @no2 char(4)
select @seqno = year(@today);
--select @No=cast(cast(right(LastId, 4)as int)+1 as nchar(4)) from Idmaster;
select @no = '2' --replaced your query from Idmaster table
select @No2= cast(left(replicate('0', 4), 4-len(@No)) as char(4))
select @seqno2 = @seqno + ltrim(rtrim(@no2)) + @no
RETURN @seqno2
END


SELECT DBO.GETID(GETDATE())
Go to Top of Page

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2010-07-11 : 07:23:27
Thank you slimt_slimt and kirsten for your help.
Go to Top of Page
   

- Advertisement -