简体   繁体   中英

Sql update column to upper lower case

I have a column called [strCustomerName]

This column has values like 'ray mantle', 'JAMES MAY', 'john DOE', 'RICHARD & Judy Miller' and so on...

I need to do an Update to the table to correct the case of all values in the selected column. The Update would then set correctly the values case to 'Ray Mantle', 'James May', 'John Doe', 'Richard & Judy Miller'

Any help doing with SQL would be great. Thanks

I would just create a function to convert your string (or names in your scenario) to CAMEL case something like below:

CREATE FUNCTION [dbo].[CamelCase]
(@Str varchar(8000))
RETURNS varchar(8000) AS
BEGIN
  DECLARE @Result varchar(2000)
  SET @Str = LOWER(@Str) + ' '
  SET @Result = ''
  WHILE 1=1
  BEGIN
    IF PATINDEX('% %',@Str) = 0 BREAK
    SET @Result = @Result + UPPER(Left(@Str,1))+
    SubString  (@Str,2,CharIndex(' ',@Str)-1)
    SET @Str = SubString(@Str,
      CharIndex(' ',@Str)+1,Len(@Str))
  END
  SET @Result = Left(@Result,Len(@Result))
  RETURN @Result
END;

Once your function is created, you could then use it in your update statement as below:

UPDATE Customer
SET strCustomerName = dbo.CamelCase(strCustomerName)

You could also call the above function in the select statement directly to check if the values are going to update correctly before running the update statement above:

select id
      ,dbo.CamelCase(strCustomerName) as CustomerName
from Customer;

Hope this helps!

SQL Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM