开发者

Select all table entries which have a fully capitalized string in a specific column?

I have a database table with a few thousand entries. A开发者_JAVA技巧 part of the entries (~20%) have been entered with a fully capitalized strings in the 'name' column.

Example:

id | name
---------
1 | THOMAS GOLDENBERG
2 | Henry Samuel
3 | GIL DOFT
4 | HARRY CRAFT
5 | Susan Etwall
6 | Carl Cooper

How would an SQL query look like that selects all entries with a fully capitalized string in the name column? (i.e. in the example: those with the ID 1,3,4)


In MySQL it would be:

SELECT id FROM table WHERE name = UPPER(name);

I think this would work the same way in SQL Server, DB2 and Postgres.


What database system?

In theory you can do a simple SELECT ... WHERE name = UPPER(name); but that does not always work. Depending on the collation of your data, you may found that all records satisfy this condition because the comparison used may be case insensitive.

You need to ensure you compare using a case sensitive collation, and the correct answer depends on the database platform you use. For example, using SQL Server syntax:

SELECT ... WHERE Name COLLATE Latin1_General_100_CS_AS = UPPER(Name);

This also works in MySQL with the condition that you use a collation name valid on MySQL.


select * from your_table where name = upper(name)


Here's a MySql function to convert uppercase to title case:

example:

update your_table set name = tcase(name) where name = upper(name);

function:

CREATE FUNCTION `tcase`(str text) RETURNS text CHARSET latin1
    DETERMINISTIC
BEGIN

  DECLARE result TEXT default '';
  DECLARE space INT default 0;
  DECLARE last_space INT default 0;

  IF (str IS NULL) THEN
    RETURN NULL;
  END IF;    

  IF (char_length(str) = 0) THEN
    RETURN '';
  END IF;

  SET result = upper(left(str,1));
  SET space = locate(' ', str);    

  WHILE space > 0 DO            
    SET result = CONCAT(result, SUBSTRING(str, last_space+2, space-last_space-1));            
    SET result = CONCAT(result, UPPER(SUBSTRING(str, space+1, 1)));        
    SET last_space = space;
    SET space = locate(' ', str, space+2);    
  END WHILE;

  SET result = CONCAT(result, SUBSTRING(str, last_space+2));

  RETURN result;

END $$    
DELIMITER ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜