SQL Server 2008 query to find rows containing non-alphanumeric characters in a column

后端 未结 3 788
情深已故
情深已故 2020-12-14 06:00

I was actually asked this myself a few weeks ago, whereas I know exactly how to do this with a SP or UDF but I was wondering if there was a quick and easy way of doing this

3条回答
  •  感动是毒
    2020-12-14 06:55

    I found this page with quite a neat solution. What makes it great is that you get an indication of what the character is and where it is. Then it gives a super simple way to fix it (which can be combined and built into a piece of driver code to scale up it's application).

    DECLARE @tablename VARCHAR(1000) ='Schema.Table'
    DECLARE @columnname VARCHAR(100)='ColumnName'
    DECLARE @counter INT = 0
    DECLARE @sql VARCHAR(MAX)
    
    WHILE @counter <=255
    BEGIN
    
    SET @sql=
    
    'SELECT TOP 10 '+@columnname+','+CAST(@counter AS VARCHAR(3))+' as CharacterSet, CHARINDEX(CHAR('+CAST(@counter AS VARCHAR(3))+'),'+@columnname+') as LocationOfChar
    FROM '+@tablename+'
    WHERE CHARINDEX(CHAR('+CAST(@counter AS VARCHAR(3))+'),'+@columnname+') <> 0'
    
    PRINT (@sql)
    EXEC (@sql)
    SET @counter = @counter + 1
    END
    

    and then...

    UPDATE Schema.Table
    SET ColumnName= REPLACE(Columnname,CHAR(13),'')
    

    Credit to Ayman El-Ghazali.

提交回复
热议问题