3

Hi I have an Access query (below) that I'm trying to recreate in SQL Server:

UPDATE tblProducts SET tblProducts.ProductCode = [tblProducts].[ProductPrefix] & 
Format([tblProducts].[ProductID],"00000")
WHERE (((tblProducts.ProductCode) Is Null Or (tblProducts.ProductCode) <>[tblProducts].[ProductPrefix] & 
Format([tblProducts].[ProductID],"00000")));

I'm having trouble with the FORMAT function.

4
  • SQL-Server or Access? Commented Aug 24, 2016 at 7:46
  • What is the difficulty you are facing? any error messages? Commented Aug 24, 2016 at 7:47
  • Sorry, the query Ive posted is an access query, im trying to recreate it in SQL Commented Aug 24, 2016 at 7:47
  • I'm getting "Format" is not a recognized built in function name Commented Aug 24, 2016 at 7:48

3 Answers 3

5

Here is one method of doing the formatting:

UPDATE tblProducts 
    SET ProductCode = [ProductPrefix] +
                      RIGHT('00000' + CAST(COALESCE(ProductId, 0) as VARCHAR(255)), 5)
WHERE ProductCode Is Null OR
      ProductCode <> [ProductPrefix] + RIGHT('00000' + CAST(ProductId as VARCHAR(255)), 5);

Actually, to prevent problems, I would phrase this as:

WITH toupdate AS (
      SELECT p.*,
             ([ProductPrefix] +
               RIGHT('00000' + CAST(COALESCE(ProductId, 0) as VARCHAR(255)), 5)
             ) as new_ProductCode
      FROM tblProducts p
     )
UPDATE toupdate
    SET  ProductCode = new_ProductCode
    WHERE ProductCode Is Null OR
          ProductCode <> new_ProductCode;
Sign up to request clarification or add additional context in comments.

Comments

2

For SQL Server 2012 and up you can use:

UPDATE tblProducts 
SET ProductCode = [ProductPrefix] + Format([ProductID],'00000')
WHERE ProductCode IS NULL OR ProductCode != [ProductPrefix] + Format([ProductID],'00000');

Another way with STUFF (SQL Server (starting with 2008)):

UPDATE tblProducts 
SET ProductCode = [ProductPrefix] + STUFF('00000' + CAST(ProductID as nvarchar(10)),1,LEN(ProductID),'')
WHERE ProductCode IS NULL OR 
    ProductCode != [ProductPrefix] + STUFF('00000' + CAST(ProductID as nvarchar(10)),1,LEN(ProductID),'')

1 Comment

Brilliant i was trying to use FORMAT() on SQL server 2008. Thanks!
2

Use this instead of format([tblProducts].[ProductID], "00000")

right('00000'+cast([tblProducts].[ProductID] as varchar(5)),5)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.