Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server - Remove End String Character "\0" From Data

I have a column in the database (SQL Server 2005) that has data with a "\0" at the end. When querying in SQL Server, this character is not visible and does not "seem" to exist. When I look in my C# code, the character is there. This character is causing an error on our website, and we need it removed from all the affected rows.

Is there a sql query I can write to easily remove this character from all the records that are affected? I can get all the affected records, but I don't have a way to update the record to a new value (without the "\0").

UPDATE: This seems to work:

Select * from TABLE
where UNICODE(SUBSTRING(naughtyField, LEN(naughtyField), 1)) = 0

So:

Update TABLE
SET naughtyField = SUBSTRING(naughtyField, 1, LEN(naughtyField) - 1)
where UNICODE(SUBSTRING(naughtyField, LEN(naughtyField), 1)) = 0
like image 604
Martin Avatar asked Aug 20 '10 17:08

Martin


People also ask

How do I remove a character at the end of a string in SQL?

Syntax: SELECT SUBSTRING(column_name,1,length(column_name)-N) FROM table_name; Example: Delete the last 2 characters from the FIRSTNAME column from the geeksforgeeks table.

How do I remove special characters from a string in SQL Server?

Replace function – using Replace function you can remove a special character from a database filed. This function only replaces a single special character.

How do I get the last 3 characters of a string in SQL?

It could be this using the SUBSTR function in MySQL: SELECT `name` FROM `students` WHERE `marks` > 75 ORDER BY SUBSTR(`name`, -3), ID ASC; SUBSTR(name, -3) will select the last three characters in the name column of the student table.

How do you get rid of nulls in SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.


1 Answers

UPDATE tbl SET col = REPLACE(col,char(0),'')

Edit: Just to redeem this answer! Might be useful for the more general case that a string has embedded \0s.

CREATE FUNCTION dbo.RemoveNullChars 
(
    @string NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX) WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE @Result NVARCHAR(MAX)
SET @Result = ''

DECLARE @counter INT

SET @counter = 0

WHILE (@counter <= LEN(@string))
    BEGIN
     IF UNICODE(SUBSTRING(@string,@counter,1)) <>  0 
        SET @Result = @Result + SUBSTRING(@string,@counter,1)
    SET @counter = @counter + 1    
    END
RETURN @Result
END

Then

 UPDATE tbl SET col = dbo.RemoveNullChars (col)
like image 143
Martin Smith Avatar answered Nov 15 '22 09:11

Martin Smith