Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 673 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Remove all spaces from a string in SQL Server

#21
It seems that everybody keeps referring to a single REPLACE function. Or even many calls of a REPLACE function. But when you have dynamic output with an unknown number of spaces, it wont work. Anybody that deals with this issue on a regular basis knows that REPLACE will only remove a single space, NOT ALL, as it should. And LTRIM and RTRIM seem to have the same issue. Leave it to Microsoft.
Here's a sample output that uses a WHILE Loop to remove ALL CHAR(32) values (space).


DECLARE @INPUT_VAL VARCHAR(8000)
DECLARE @OUTPUT_VAL VARCHAR(8000)

SET @INPUT_VAL = ' C A '
SET @OUTPUT_VAL = @INPUT_VAL
WHILE CHARINDEX(CHAR(32), @OUTPUT_VAL) > 0 BEGIN
SET @OUTPUT_VAL = REPLACE(@INPUT_VAL, CHAR(32), '')
END

PRINT 'START:' + @INPUT_VAL + ':END'
PRINT 'START:' + @OUTPUT_VAL + ':END'

Here's the output of the above code:

START: C A :END
START:CA:END

Now to take it a step further and utilize it in an UPDATE or SELECT statement, change it to a udf.

CREATE FUNCTION udf_RemoveSpaces (@INPUT_VAL VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN

DECLARE @OUTPUT_VAL VARCHAR(8000)
SET @OUTPUT_VAL = @INPUT_VAL
-- ITTERATE THROUGH STRING TO LOOK FOR THE ASCII VALUE OF SPACE (CHAR(32)) REPLACE IT WITH BLANK, NOT NULL
WHILE CHARINDEX(CHAR(32), @OUTPUT_VAL) > 0 BEGIN
SET @OUTPUT_VAL = REPLACE(@INPUT_VAL, CHAR(32), '')
END

RETURN @OUTPUT_VAL
END

Then utilize the function in a SELECT or INSERT statement:

UPDATE A
SET STATUS_REASON_CODE = WHATEVER.dbo.udf_RemoveSpaces(STATUS_REASON_CODE)
FROM WHATEVER..ACCT_INFO A
WHERE A.SOMEVALUE = @SOMEVALUE

INSERT INTO SOMETABLE
(STATUS_REASON_CODE)
SELECT WHATEVER.dbo.udf_RemoveSpaces(STATUS_REASON_CODE)
FROM WHATEVER..ACCT_INFO A
WHERE A.SOMEVALUE = @SOMEVALUE
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through