简体   繁体   中英

Removing spaces from strings over a certain length

I have a column in my SQL Server database which determines the folder structure of a group of files. So for example the column would display the following:

\(folder 1)\(folder 2)\(folder3)\
\(folder 1)\(folder 2)\(folder3)\(folder 4)
\(folder 1)\(folder 2)\

The problem is that a single folder name must not be over 50 characters long. If it is, I'd like to remove all the spaces from that folder (but only for that folder).

So if in the first example folders 1 and 3 were under 50 characters long but folder 2 was over 50 characters long then folders 1 and 3 would remain the same and folder 2 would have spaces removed.

That's my priority at the moment but if possible, I'd like to remove '-' and '_' but only in cases where removing spaces isn't enough to lower the character count to the 50 limit.

Is there an easy way of doing this without using multiple used of SUBSTRING , CHARINDEX and CASE ?

Any help would be highly appreciated.

I came up with the following piece of code, I think that should solve your problem. Ping me if you have any queries

 DECLARE @InputString NVARCHAR(300) = 'Hello\Hello World\He He'
 DECLARE @FolderName NVARCHAR(255)
 DECLARE @pos INT
 DECLARE @UpdatedString NVARCHAR(300) = '' 
 DECLARE @Size INT = 50

 SET @InputString = CONCAT(@InputString, '\')
 WHILE CHARINDEX('\', @InputString) > 0
 BEGIN
  SELECT @pos  = CHARINDEX('\', @InputString)  
  SELECT @FolderName = SUBSTRING(@InputString, 1, @pos-1)

  IF(LEN(@FolderName) > @Size)
  BEGIN
    SET @FolderName = REPLACE(@FolderName, ' ', '')
  END

  SET @UpdatedString = CONCAT(@UpdatedString, @FolderName, '\')

  SET @InputString = SUBSTRING(@InputString, @pos+1, LEN(@InputString)-@pos)
 END

 Set @UpdatedString = SUBSTRING(@UpdatedString, 0, LEN(@UpdatedString))

 SELECT @UpdatedString

I think the variable names are pretty straight forward in themselves.

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