4

In C#, if I do:

string code = string.format("C{0:000}", 7);

The result will be: C007

Is there a function in SQL Server that does the same thing? Or do I have to create a function myself?

6
  • 5
    why not do formatting on c# side Commented Oct 2, 2014 at 19:52
  • If you're looking for an exact match, a CLR UDF may be the way to go. Commented Oct 2, 2014 at 19:54
  • TIme to update. Not in SQL 2005, but 2014 has a format function EXTREMELY similar to C#. Commented Oct 2, 2014 at 20:16
  • 2
    SQL Server 2012 and newer have a FORMAT function ..... Commented Oct 2, 2014 at 20:22
  • possible duplicate of Is there a way to get dates with custom formats in SQL Server? Commented Oct 2, 2014 at 20:28

4 Answers 4

6

Use FORMATMESSAGE() function.

SELECT FORMATMESSAGE('This is the %s and this is the %s.', 'first variable', 'second variable') AS Result; 

https://msdn.microsoft.com/en-us/library/ms186788.aspx

Sign up to request clarification or add additional context in comments.

Comments

3

In straight TSQL, there is nothing as powerful as the C# string.format. The CONVERT() function offers some limited formatting, but for anything it can't handle you'd have to write your own function. Google "SQL String functions" to see what tools you have in your SQL arsenal.

1 Comment

Or, don't perform this formatting in the database in the first place.
0

I would use REPLICATE, combined with RIGHT

'C' + RIGHT(REPLICATE('0', <Padding Amount Here>) + CAST(7 AS NVARCHAR(10)), <Padding Amount Here>)

Usage:

'C' + RIGHT(REPLICATE('0', 10) + CAST(7 AS NVARCHAR(10)), 10)

Produces the follow:

C0000000007

1 Comment

Added length + switched to NVARCHAR
0

SELECT 'C' + RIGHT('00' + CONVERT(varchar(3),7),3)

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.