Solved

Formula in computed column. How to

Posted on 2009-07-13
28
524 Views
Last Modified: 2012-05-07
Hi

I am trying for the first time to use computed columns in Sql Server. This I need to create Order numbers and account numbers.
This one works:
(isnull(N'ON'+CONVERT([nvarchar](100),[CustomerID],(0)),N'*** ERROR ***'))
It creates a ordernumber ON(CustomerID) ...no problem.
What i want is to add more values. Like I would like to include Year() (current year when order or account war created) and maybe some more. How do I include more then one value in the formula?
0
Comment
Question by:ize_man
  • 13
  • 11
  • 2
  • +1
28 Comments
 
LVL 26

Expert Comment

by:tigin44
ID: 24838634
(isnull(N'ON'+CONVERT([nvarchar](100),[CustomerID],(0)),N'*** ERROR ***')) + DATEPART(YEAR, GETDATE())
0
 
LVL 26

Expert Comment

by:tigin44
ID: 24838662
you can use any valid sql opeartion in computed columns. ie as in above post
0
 

Author Comment

by:ize_man
ID: 24838716
No, sorry :( not working. I have created a function to add zeroz to the account number i am creating but would weary much like to add year as well...this makes the account numbers start over each year. This formula gives me account number : CN00000000 (o minus customerID)
(isnull('CN'+[Buisness].[ufnLeadingZeros]([CustomerID]),''))

if you want here you have the function in the code widow.

I have tried to add DATEPART(YEAR,GETDATE()) section in the formula in various ways but have not succeeded yeat :)


USE [TT_Online]

GO
 

/****** Object:  UserDefinedFunction [Buisness].[ufnLeadingZeros]    Script Date: 07/13/2009 13:23:16 ******/

SET ANSI_NULLS ON

GO
 

SET QUOTED_IDENTIFIER ON

GO
 
 

CREATE FUNCTION [Buisness].[ufnLeadingZeros](

    @Value int

) 

RETURNS varchar(8) 

WITH SCHEMABINDING 

AS 

BEGIN

    DECLARE @ReturnValue varchar(8);
 

    SET @ReturnValue = CONVERT(varchar(8), @Value);

    SET @ReturnValue = REPLICATE('0', 8 - DATALENGTH(@ReturnValue)) + @ReturnValue;
 

    RETURN (@ReturnValue);

END;
 

GO

Open in new window

0
 

Author Comment

by:ize_man
ID: 24838727
I tried this but get following error message :- Error validating the formula for column 'Ordenumber'. ...always.

This is the formula: (isnull('CN'+[Buisness].[ufnLeadingZeros]([CustomerID]),'')) + DATEPART(YEAR, GETDATE())

I can see that there is a Year() function wich takes datetime param and i can't use that either Year(getdate()) ??
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24839595
Try :

DATENAME(YEAR,GETDATE())

It returns a string value of the year, not an integer value of the year.
0
 

Author Comment

by:ize_man
ID: 24839967
Yes, this works fine :) one more question, how do i get it in right after 'CN' part or maybe before?? I have tried now but just cant get it to work
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24840135
What do you mean ?


Would be more inclined to be doing :

'CN' + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(customerid,0)),8)
0
 

Author Comment

by:ize_man
ID: 24840629
I mean this

This statement:
(isnull('CN'+[Buisness].[ufnLeadingZeros]([CustomerID]),'')+datename(year,getdate()))

gives me CN000012212009 if CustomerID is 1221 what i would like to do is move 2009 like this:
CN200900001221 as an example
0
 

Author Comment

by:ize_man
ID: 24840634
this does not work
'CN' + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(customerid,0)),8)
0
 

Author Comment

by:ize_man
ID: 24840749
Ok, stupid me :-| i got it to work...a little syntax problem ;-) Solution
(isnull(('CN'+datename(year,getdate()))+[Buisness].[ufnLeadingZeros]([CustomerID]),''))

had one bracket to much ;-) Problem solved. Today i learned something new.. ;-)))
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24840774
would need to be in brackets...

What does it give you ?

If you want to use the function... then...

(isnull('CN'+datename(year,getdate())+[Buisness].[ufnLeadingZeros]([CustomerID]),''))
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24840783
Sorry about that... Didn't see your previous posting (snail mail here).
0
 

Author Comment

by:ize_man
ID: 24840824
The best might be to include the year into the function...I tried that as well but could not get it to work
0
 

Author Comment

by:ize_man
ID: 24840847
tried this as well but it did not work
(isnull('CN' + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(customerid,0)),8) )
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 51

Accepted Solution

by:
Mark Wills earned 500 total points
ID: 24840889
No that won't work. The isnull() requires two arguments, you have only one...

ALTER FUNCTION [ufnLeadingZeros](@Value int)
RETURNS varchar(12)
WITH SCHEMABINDING
AS
begin
RETURN (DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(@value,0)),8));
end
GO


0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24840946
Or even :


ALTER FUNCTION [ufnLeadingZeros](@prefix char(2),@Value int)
RETURNS varchar(14)
WITH SCHEMABINDING
AS
begin
RETURN (@Prefix + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(@value,0)),8));
end
GO

-- then use it as per :

select business.ufnleadingzeros ('CN',123)

-- or

(isnull(business.ufnleadingzeros ('CN',customerid),''))

-- the isnull is really not doing anything...
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24841071
Not sure why you are getting the other error...  this seems to work fine :

create table my_computed_column (id int identity, customerid int, date datetime, cn_number as 'CN' + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(customerid,0)),8) )

insert my_computed_column (customerid, date) values (123,getdate())

insert my_computed_column (date) values (getdate())

select * from my_computed_column

update my_computed_column set customerid = 321 where customerid is NULL

select * from my_computed_column
0
 

Author Comment

by:ize_man
ID: 24841110
I tried this:
(isnull(business.ufnleadingzeros ('CN',customerid),'')) and could not get it to work (mine: "(isnull(Business.ufnLeadingZerosCurrYear ('CN',CustomerId),'')) ") otherwise i think this is the best solution... there was no problem crating the function  
0
 

Author Comment

by:ize_man
ID: 24841141
Yes...worked fine :-) ...must be syntax failure in mine
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24841149
Functions do create a bit of overhead, not the friendliest of beasts as a scaler function....

But, so long as you have a solution, and it is working, it is more important that it actually works :)
0
 

Author Comment

by:ize_man
ID: 24841174
Yes...thank you :-)
0
 

Author Closing Comment

by:ize_man
ID: 31602753
With a great thanks for the lesson :-)
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24841290
A pleasure working with you, and happy I have been of assistance...
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 24846319
You don't need a function to generate the values you need you can use directly in the computed column the formula:

'CN'+cast(cast(year(getdate()) as bigint)*100000000+isnull(customerid,0) as varchar)

you can test with

select 'CN'+cast(cast(year(getdate()) as bigint)*100000000+isnull(1221,0) as varchar)


PS. I know it was answered but I didn't like the solution. No offence Mark. :o)
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24847412
None taken, I do not like the function either and was trying hard for : 'CN' + DATENAME(YEAR, GETDATE()) + right('00000000'+convert(varchar,isnull(customerid,0)),8)

But for whatever reason the Asker had more success with the Askers own function, and so let that happen - it worked for the Asker whereas other suggestions didn't.
 
And, I will always welcome a good open discussion / (constructive) criticism :)
0
 

Author Comment

by:ize_man
ID: 24847454
Hi guys

It actually worked after a while...and exercises from me... I don't know why it would not work before but it doe's now. The only thing is that i can not set NOT NULL property to true otherwise it works fine :-)

(('CN'+datename(year,getdate()))+right('00000000'+CONVERT([varchar],isnull([customerid],(0)),0),(8)))
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 24847941
Well that is fantastic news, so much better without the function. Well done for persevering with it.
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 24849879
You cannot set the NOT NULL property on a computed column but you can make sure that it will never happen in your formula, which you did. ;o)
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now