使用IndexOf和/或Substring将数据解析为单独的列

时间:2013-04-30 18:33:26

标签: tsql substring indexof

我正致力于将数据从一个数据库迁移到另一个数据库以供医院使用。在旧数据库中,医生的专业ID都在一列(swvar_specialties)中,每列都用逗号分隔。在新数据库中,每个专业ID都有自己的列(例如:Specialty1_PrimaryID,Specialty2_PrimaryID,Specialty3_PrimaryID等)。我试图从旧数据库导出数据,并将这些数据分成这些单独的列。我知道我可以使用indexofsubstring来执行此操作 - 我只需要语法方面的帮助。

所以这个查询:

Select swvar_specialties as Specialty1_PrimaryID
From PhysDirectory

可能会返回类似于39,52,16的结果。我需要此查询才能在结果中显示Specialty1_PrimaryID = 39Specialty2_PrimaryID = 52Specialty3_PrimaryID = 16。以下是我目前的查询。我最终将有一个联盟从专业表中拉出专业名称。我只需要先解决这个问题。

 Select pd.ref as PrimaryID, pd.swvar_name_first as FirstName, pd.swvar_name_middle as   MiddleName, 
 pd.swvar_name_last as LastName, pd.swvar_name_suffix + ' ' + pd.swvar_name_degree as NameSuffix, 
 pd.swvar_birthdate as DateOfBirth,pd.swvar_notes as AdditionalInformation, 'images/' + '' + pd.swvar_photo as ImageURL, 
 pd.swvar_philosophy as PhilosophyOfCare, pd.swvar_gender as Gender, pd.swvar_specialties as Specialty1_PrimaryID, pd.swvar_languages as Language1_Name 
 From PhysDirectory as pd

1 个答案:

答案 0 :(得分:0)

文章Split function equivalent in T-SQL?提供了有关如何使用拆分函数拆分逗号分隔字符串的一些详细信息。

通过修改本文中提供的表值函数来提供标识列,我们可以定位特定行,例如Specialty1_PrimaryID:

/*
    Splits string into parts delimitered with specified character.
*/
CREATE FUNCTION [dbo].[SDF_SplitString]
(
    @sString nvarchar(2048),
    @cDelimiter nchar(1)
)
RETURNS @tParts TABLE (id bigint IDENTITY, part nvarchar(2048) )
AS
BEGIN
    if @sString is null return
    declare @iStart int,
        @iPos int
    if substring( @sString, 1, 1 ) = @cDelimiter 
    begin
        set @iStart = 2
        insert into @tParts
        values( null )
    end
    else 
        set @iStart = 1
        while 1=1
        begin
            set @iPos = charindex( @cDelimiter, @sString, @iStart )
            if @iPos = 0
            set @iPos = len( @sString )+1
            if @iPos - @iStart > 0          
            insert into @tParts
                values  ( substring( @sString, @iStart, @iPos-@iStart ))
            else
            insert into @tParts
                values( null )
            set @iStart = @iPos+1
            if @iStart > len( @sString ) 
            break
        end
    RETURN
END

您的查询可以使用此拆分功能,如下所示:

Select 
    pd.ref as PrimaryID, 
    pd.swvar_name_first as FirstName, 
    pd.swvar_name_middle as   MiddleName, 
    pd.swvar_name_last as LastName, 
    pd.swvar_name_suffix + ' ' + pd.swvar_name_degree as LastName, 
    pd.swvar_birthdate as DateOfBirth,pd.swvar_notes as AdditionalInformation,
    'images/' + '' + pd.swvar_photo as ImageURL, 
    pd.swvar_philosophy as PhilosophyOfCare, pd.swvar_gender as Gender, 
    (Select part from SDF_SplitString(pd.swvar_specialties, ',') where id=1) as Specialty1_PrimaryID, 
    (Select part from SDF_SplitString(pd.swvar_specialties, ',') where id=2) as Specialty2_PrimaryID,
    pd.swvar_languages as Language1_Name 
From PhysDirectory as pd