将lastname,firstname middleinitial转换为sql中的不同列

时间:2016-07-07 17:34:36

标签: sql sql-server sql-server-2014-express

我目前有一个名为PersonFullName的列。它的数据如下:

PERSONFULLNAME  
Doe, John A  
Doe, Jane M  
Doe, Eric

我想以这种格式获取数据:

LastName  -  FirstName  -  MI  
DOE    -     John    -     A  
DOE    -     Jane    -     M  
Doe    -     Eric

下面显示正常,但是如果我添加一个中间的首字母,则中间的首字母落在名字列中。

declare @last as varchar(20)
declare @first as varchar(20)
declare @mid as varchar(20)

declare @name varchar(100)
select @name = 'Leake, Angela'

set @last = substring(@name, 1,charindex(', ',@name)-1)
set @first = LTRIM(substring(@name, charindex(' ',@name),len(@name)-charindex(' ',@name)+1))
set @mid = RIGHT(@name, CHARINDEX(' ', REVERSE(@name))-1)
If (@mid=@first) SET @mid=''

select @last as 'Last Name', @first as 'First Name',@mid as 'Middle Name'

Select PERSONFULLNAME FROM Kronos

1 个答案:

答案 0 :(得分:1)

是的okomikeruko有效。我还在学习SQL,所以我不知道CTE。

以下完全符合我的要求......

<tr>
         <td headers="header1" class="text-center vertical-center"> 7:00 </td>
        <td headers="header2" class="media vertical-center"><span class="pull-left"><img class="media-object" height="35" width="35" src="/weathericons/small/02.png" /></span><div class="visible-xs visible-sm">
            <br />
            <br />
          </div>
          <div class="media-body">
            <p>Partly Cloudy</p>
          </div>
        </td>
        <td headers="header3m" class=" metricData text-center vertical-center">23
                                            �(22.9)
                                        </td>
        <td headers="header3i" class=" imperialData hidden text-center vertical-center">73
                                            �(73.2)
                                        </td>
        <td headers="header4m" class="metricData text-center vertical-center">
          <abbr title="West-Northwest">WNW</abbr> 8</td>
        <td headers="header4i" class="imperialData hidden text-center vertical-center">
          <abbr title="West-Northwest">WNW</abbr> 5</td>
        <td headers="header6" class="metricData text-center vertical-center">30</td>
        <td headers="header6" class="imperialData hidden text-center vertical-center">87</td>
        <td headers="header7" class="text-center vertical-center">83</td>
        <td headers="header8" class="metricData text-center vertical-center">20</td>
        <td headers="header8" class="imperialData hidden text-center vertical-center">68</td>
        <td headers="header9m" class="metricData text-center vertical-center">100.7</td>
        <td headers="header9i" class="imperialData hidden text-center vertical-center">29.7</td>
        <td headers="header10" class="metricData text-center vertical-center">24</td>
        <td headers="header10" class="imperialData hidden text-center vertical-center">15</td>
      </tr>