简体   繁体   中英

Padding with leading and trailing spaces all values of column in SQL

For a column in a table, I want to add leading & trailing spaces to all the values of the column in one go. For example, table Employee(Name varchar(5)) . As table is having 5 characters each in a row, On executing a query it should be updated to 7 characters each in a row. Infact leading & trailing spaces should be padded to the values in the column.

I need an SQL query.

select ' '||Name||' ' from Employee

如果要更新表

update EMPLOYEE set Name = ' ' || Name || ' '

In Oracle, this will put a single space in front of every value in the "name" column, and right pad it with spaces to a total length of 7 characters:

update employee
set name = rpad(' '||name,7);

You'll need to alter the table first to accommodate the extra spaces.

alter table employee
modify
name varchar2(7);
UPDATE EMPLOYEE
SET Name = ' ' || Name || ' '

Since the column that needs to be padded is of variable length I do not believe hard coding a space before or after would be the correct solution. If the data in the column has a length of 3, padding 1 space before and after the data will still result in a length of 5. Since the OP did not specify if all of the data has a length of 5 a different approach is needed. Depending on how you want spaces added you could try the following (this adds 1 space before the data and pads the remaining spaces to the end):

Declare @Name varchar(5) = 'Bob'        
Select ' ' + @Name + REPLICATE(' ',(6 - LEN(@NAME))) as NewName

This results in 1 space before the name and 3 spaces after.

Where is the data coming from? If you make the width of the column fixed, any leading spaces in the source data should carry over. (DISCLAIMER: I am working in SQL Server 2012, not Oracle.) I had an issue where I was sending the data from SQL server to an AS400 DB2 database, and the programs running from the data expect things to line up in certain columns. Trimming leading spaces mis-aligns the whole row. When my SQL server data type was NVARCHAR(20), the "VAR" part trimmed the leading spaces. Making it NCHAR(20) fixed that problem. The DB2 Database removed the spaces though, so I am having issues on that end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM