对sproc进行故障排除后,我意识到字段有一个额外的字符,我假设空白或者某些特殊字符不可见。例如,city字段包含值'Abbeville',其长度(LEN([city])为10.我以为我可以使用以下内容修剪空白区域:
UPDATE US_City_State
SET [City] = RTRIM(LTRIM([City]))
那不起作用。我转向varbinary但我不知道该怎么做。该列定义为nvarchar。这是演员值。
0x4100620062006500760069006C006C006500A000
[更新]样本数据
City City_Hex_Value
Aaronsburg 0x4100610072006F006E0073006200750072006700A000
Abbeville 0x4100620062006500760069006C006C006500A000
谢谢!
答案 0 :(得分:8)
也许空白不仅仅是一个空间:
试试这个:
UPDATE US_City_State
SET [City] = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE([City], CHAR(10), ''), CHAR(13), ''), CHAR(9), ''), CHAR(160), '')))
<强>说明:强> 一些空白区域并不是真正的空间(&#39;&#39;)。以下是一些空白:
CHAR(9) = Horizontal Tab
CHAR(10) = Line Feed
CHAR(13) = Carriage Return
CHAR(160) = Non-Breaking Space
我做的是删除上面的空格。您可以按空格(&#39;&#39;)或CHAR(32)
替换它,具体取决于您希望如何处理它们。
答案 1 :(得分:0)
TRIM
所有SPACE
的{{1}}和TAB
:
ENTER
DECLARE @Str VARCHAR(MAX) = '
[ Foo ]
'
DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
CHAR(13) + CHAR(10) -- ENTER
+ CHAR(9) -- TAB
+ ' ' -- SPACE
;WITH Split(Chr, Pos) AS (
SELECT
SUBSTRING(@Str, 1, 1) AS Chr
, 1 AS Pos
UNION ALL
SELECT
SUBSTRING(@Str, Pos, 1) AS Chr
, Pos + 1 AS Pos
FROM Split
WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
Pos >= (
SELECT MIN(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
AND Pos <= (
SELECT MAX(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
SELECT '"' + @NewStr + '"'
CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
DECLARE @NewStr VARCHAR(MAX) = NULL
IF (@Str IS NOT NULL) BEGIN
SET @NewStr = ''
DECLARE @WhiteChars VARCHAR(4) =
CHAR(13) + CHAR(10) -- ENTER
+ CHAR(9) -- TAB
+ ' ' -- SPACE
IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN
;WITH Split(Chr, Pos) AS (
SELECT
SUBSTRING(@Str, 1, 1) AS Chr
, 1 AS Pos
UNION ALL
SELECT
SUBSTRING(@Str, Pos, 1) AS Chr
, Pos + 1 AS Pos
FROM Split
WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
Pos >= (
SELECT MIN(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
AND Pos <= (
SELECT MAX(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
END
END
RETURN @NewStr
END
<强>结果强>
-- Test
DECLARE @Str VARCHAR(MAX) = '
[ Foo ]
'
SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim(' ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'