Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query for finding rows with special characters only

Tags:

sql

sql-server

I am working with SQL Server 2005.

I need to find out only those rows for which there is a special character in “Body” column. In the following scenario, the result should be only the row with TemplateID = 2. How do we write the query for this?

CREATE TABLE #Template (TemplateID INT, Body VARCHAR(100))

INSERT INTO #Template (TemplateID,Body) VALUES (1,'abcd  1234')

INSERT INTO #Template (TemplateID,Body) VALUES (2,'#^!@')

Anything other than the following is a special character for this scenario

1) Alphabtes

2) Digits

3) Space
like image 787
Lijo Avatar asked Jun 03 '10 16:06

Lijo


People also ask

How do I select a special character in a row in SQL?

If special characters are number( 0-9 ) and these characters ( '" ) than you could write select F_name from yourtable WHERE F_name LIKE '%[0-9''"]% .

How do you handle special characters in SQL query?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

How do I get only characters in a string in SQL?

The SUBSTRING() function extracts some characters from a string.


1 Answers

SELECT
    TemplateID,
    Body
FROM
    #Template
WHERE
    Body LIKE '%[^0-9a-zA-Z ]%'

The stuff between the brackets says numbers (0-9), lowercase alphas (a-z), uppercase alphas (A-Z) and the space. The "^" makes that a "NOT" one of these things. Note that this is different though than NOT LIKE '%[0-9a-zA-Z ]%'

like image 101
Tom H Avatar answered Sep 23 '22 06:09

Tom H