解析姓氏,名字和截断和上限

时间:2014-11-10 20:31:02

标签: sql sql-server tsql

我有一个字段将客户名称存储在一列中:John,Dao。名称存储为Lastname,FirstName。

我需要做的是在CAPS中列出姓氏,截断为10个字符,然后是第一个名字的首字母(第一个首字母大写字母)。例如John,Dao需要显示为JOHN D。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情......

DECLARE @FullName varchar(50) = 'Smithxxxxxxxxx, John';

SELECT UPPER(SUBSTRING(SUBSTRING(@FullName, 1, CHARINDEX(',', @FullName)-1), 1, 10) ) as LastName
, UPPER( LTRIM( SUBSTRING(@FullName, CHARINDEX(',', @FullName) +1, 2))) as FirstName

答案 1 :(得分:1)

--Example 1 
    DECLARE @FullName VARCHAR(50) = 'Smithxxxxxxxxx, John';

    SELECT  UPPER(LEFT(@FullName,
                       CHARINDEX(',', @FullName) - 1)) AS LastName ,
            UPPER(LEFT(REPLACE(RIGHT(@FullName,
                                     LEN(@FullName)
                                     - CHARINDEX(',',
                                        @FullName) - 1),
                               ', ', ''), 1)) AS FirstName
-------------------------------------
--Example 2
    DECLARE @FullName VARCHAR(50) = 'Smithxxxxxxxxx, John';

    SELECT  UPPER(LEFT(@FullName,
                       CHARINDEX(',', @FullName) - 1)) AS LastName ,
            UPPER(LEFT(REPLACE(REVERSE(LEFT(REVERSE(@FullName),
                                        CHARINDEX(',',
                                        REVERSE(@FullName)))),
                               ', ', ''), 1)) AS FirstName

答案 2 :(得分:0)

这是SQLite中的一个例子:

sqlite> create table customer(lastname string, firstname string);
sqlite> insert into customer values("VerylongNameIndeed", "alex");
sqlite> SELECT UPPER(SUBSTR(lastname, 1, 10)), UPPER(SUBSTR(firstname, 1, 1)) FROM customer;

结果:VERYLONGNA|A

编辑:我刚刚意识到这些名称都存储在问题的一个列中,所以这里是以上的修订版本:

sqlite> create table customer(name string);
sqlite> insert into customer values("john, dao");
sqlite> insert into customer values("VeryLongName, alex");
sqlite> SELECT UPPER(SUBSTR(name, 1, MIN(10, INSTR(name, ",")-1))), UPPER(SUBSTR(name, INSTR(name, ",")+2, 1)) FROM customer;

结果:

JOHN|D
VERYLONGNA|A