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

后端 未结 3 784
情深已故
情深已故 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:36

    Sql server has very limited Regex support. You can use PATINDEX with something like this

    PATINDEX('%[a-zA-Z0-9]%',Col)
    

    Have a look at PATINDEX (Transact-SQL)

    and Pattern Matching in Search Conditions

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 06:56

    Won't this do it?

    SELECT * FROM TABLE
    WHERE COLUMN_NAME LIKE '%[^a-zA-Z0-9]%'
    

    Setup

    use tempdb
    create table mytable ( mycol varchar(40) NULL)
    
    insert into mytable VALUES ('abcd')
    insert into mytable VALUES ('ABCD')
    insert into mytable VALUES ('1234')
    insert into mytable VALUES ('efg%^&hji')
    insert into mytable VALUES (NULL)
    insert into mytable VALUES ('')
    insert into mytable VALUES ('apostrophe '' in a sentence') 
    
    SELECT * FROM mytable
    WHERE mycol LIKE '%[^a-zA-Z0-9]%'
    
    drop table mytable 
    

    Results

    mycol
    ----------------------------------------
    efg%^&hji
    apostrophe ' in a sentence
    
    0 讨论(0)
提交回复
热议问题