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
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.
Replace function – using Replace function you can remove a special character from a database filed. This function only replaces a single special character.
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.
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.
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 \0
s.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With