Avatar of dsoderstrom
 asked on

How to format and concatenate fields in an SQL server view

I am creating a view in an SQL server database and need to combine two fields to create a new field.  The two fields are AccountingPeriod which is a a smallint field which can contain the values 0 through 12 and AccountingYear which is a smallint field containing the four digit year.
I want to use these fields to create a new char(4) field which is the period and the last two digits of the year (ex. AccountingPeriod 3 and AccountingYear 2011 would become "0311")
What is the syntax that I would use to create this field
Microsoft AccessMicrosoft SQL Server 2005

Avatar of undefined
Last Comment

8/22/2022 - Mon

select '0' + right(cast(isnull(AccountingPeriod, 0) as nvarchar(2)), 2) + right(cast(AccountingYear as nvarchar(4)), 2) as periodyear

I had to remove the "select" at the beginning of your code and the "as periodyear" at the end in order for my view to work.  So I end up with the following:

'0' + RIGHT (CAST(ISNULL(dbo.FS_GLBatchHeader.AccountingPeriod, 0) AS nvarchar(2)), 2) + RIGHT (CAST(dbo.FS_GLBatchHeader.AccountingYear AS nvarchar(4)), 2)

This works except for when the AccountingPeriod is a 2 charactor month.  For example, if the AccountingPeriod is 12 and the year is 2010, I get "01210".  I need it to be "1210".
 What do I need to change?

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy