Convert

Hi,

I am trying to do an update to the table below, in that I insert the value of Field1 into Field2 minus 1.
Both fields are CHAR(3), hence the convert. The result I get is B5, when I am trying to get B05.  Any guidance on the syntax would be appreciated.
UPDATE Tab1
                  SET       Field1 = 'B' + RIGHT('00' + (CONVERT(INT,RIGHT(Field2,2))-1),2)
                  WHERE   Field2 IS NULL;

Thanks
Morpheus7Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
UPDATE Tab1
                   SET       Field1 = 'B' + RIGHT('00' + CAST(RIGHT(Field2,2)-1 AS varchar(2)),2)
                   WHERE   Field2 IS NULL;

Btw, unless you need to index this value, instead of actually storing it you could use a computed column that dynamically sets the value when it is needed:

ALTER TABLE Tab1
ADD CAST(Field1 AS 'B' + RIGHT('00' + CAST(RIGHT(Field2,2)-1 AS varchar(2)),2) AS char(3))
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you need to reconvert the INT value back to VARCHAR before you concat it to the '00'
UPDATE Tab1
                  SET       Field1 = 'B' + RIGHT('00' + CONVERT ( VARCHAR(10), CONVERT(INT,RIGHT(Field2,2))-1)  ,2)
                  WHERE   Field2 IS NULL;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Scott PletcherSenior DBACommented:
Hmm, shouldn't the WHERE clause be:

WHERE   Field2 IS NOT NULL;

Otherwise Field1 will always be set to NULL, since Field2 is NULL.
PortletPaulEE Topic AdvisorCommented:
>>"I insert the value of Field1 into Field2 minus 1"

If there is a value in feld1 and field2 is null then the where clause is good, but the sequence of the set operation is backwards

UPDATE Tab1
                  SET       Field2 = 'B' + RIGHT('00' + CONVERT ( VARCHAR(2), CONVERT(INT,RIGHT(Field1,2))-1)  ,2)
                  WHERE   Field2 IS NULL;
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.