1

我正在为医院将数据从一个数据库迁移到另一个数据库。在旧数据库中,医生的专业 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
4

1 回答 1

0

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

通过修改本文中介绍的表值函数以提供标识列,我们可以定位特定行,例如 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
于 2013-04-30T19:39:31.383 回答