2013-04-30 45 views
1

我正在将数据从一个数据库迁移到另一个数据库以用于医院。在旧的数据库中,医生的专业ID全部位于一列(swvar_specialties)中,每个都用逗号分隔。在新的数据库中,每个专业ID都会有自己的专栏(例如:专业1_PrimaryID,专业2_PrimaryID,专业3_PrimaryID等)。我正试图从旧数据库中导出数据,并将这些数据分隔到这些单独的列中。我知道我可以使用indexofsubstring来做到这一点 - 我只需要语法帮助。使用IndexOf和/或Substring将数据解析到单独的列中

所以这个查询:

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 
+0

只有一个评论,但专业的多列不是第3范式。应该有DrID,SpecialtyID表,Dr博士可以有零或许多专业。 – Paparazzi 2013-04-30 19:28:07

回答

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, @[email protected])) 
      else 
      insert into @tParts 
       values(null) 
      set @iStart = @iPos+1 
      if @iStart > len(@sString) 
      break 
     end 
    RETURN 
END 

你的查询可以利用这种分裂的功能如下:

​​