📜  tsql pad left - SQL (1)

📅  最后修改于: 2023-12-03 15:05:38.100000             🧑  作者: Mango

T-SQL PAD LEFT - SQL

When it comes to formatting data in SQL Server, developers often encounter the need to pad strings left with a certain character or set of characters. This is where the T-SQL PAD LEFT function or the STUFF function comes in handy.

T-SQL PAD LEFT Function

The T-SQL PAD LEFT function is used to pad a string left with a specific character or set of characters. The syntax for the function is as follows:

SELECT
   PADLEFT(string, length, padding)
FROM
   table_name;
  • string: The original string that needs to be padded left.
  • length: The total length of the resulting string after padding.
  • padding: The character or set of characters that are used to pad the original string.

For example, to pad the string '123' left with zeros to a total length of 5, we can use the following query:

SELECT
   PADLEFT('123', 5, '0')

This will return the string '00123'.

STUFF Function

Another way to achieve padding left is by using the STUFF function in T-SQL. The STUFF function is used to replace a part of a string with another string. We can use this function to replace the left portion of a string with a padding character or set of characters.

The syntax is as follows:

SELECT
   STUFF(string, start, length, new_string)
FROM
   table_name;
  • string: The original string that needs to be padded left.
  • start: The position in the string where padding should begin.
  • length: The number of characters to replace with padding characters.
  • new_string: The string that replaces the characters starting from the start position.

For example, to pad the string '123' left with zeros to a total length of 5, we can use the following query:

SELECT
   STUFF('123', 1, 0, '00')

This will return the string '00123'.

Conclusion

The T-SQL PAD LEFT function and the STUFF function are great tools for formatting data in SQL Server. Choosing the appropriate function depends on the specific data needs and preferences of the developer.