Tsql 使用IndexOf和/或Substring将数据解析为单独的列
我正在为医院将数据从一个数据库迁移到另一个数据库。在旧数据库中,医生的专业ID都在一列(swvar_specialties)中,每个都用逗号分隔。在新数据库中,每个专业ID都有自己的列(例如:Specialty1_PrimaryID、Specialty2_PrimaryID、Specialty3_PrimaryID等)。我试图将数据从旧数据库中导出,并将其分离到这些单独的列中。我知道我可以使用Tsql 使用IndexOf和/或Substring将数据解析为单独的列,tsql,substring,indexof,Tsql,Substring,Indexof,我正在为医院将数据从一个数据库迁移到另一个数据库。在旧数据库中,医生的专业ID都在一列(swvar_specialties)中,每个都用逗号分隔。在新数据库中,每个专业ID都有自己的列(例如:Specialty1_PrimaryID、Specialty2_PrimaryID、Specialty3_PrimaryID等)。我试图将数据从旧数据库中导出,并将其分离到这些单独的列中。我知道我可以使用indexof和substring来实现这一点-我只需要语法方面的帮助 所以这个查询: Select s
indexof
和substring
来实现这一点-我只需要语法方面的帮助
所以这个查询:
Select swvar_specialties as Specialty1_PrimaryID
From PhysDirectory
可能会返回类似于39,52,16的结果。我需要此查询在结果中显示Specialty1\u PrimaryID=39
,Specialty2\u PrimaryID=52
,以及Specialty3\u PrimaryID=16
。以下是我到目前为止的疑问。我最终将有一个连接从specialties表中提取专业名称。我只需要先解决这个问题
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
本文提供了有关如何使用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
只有一条注释,但专业的多列不是第三种正常形式。应该有一张带有DrID、SpecialtId的桌子,这样Dr就可以没有或有很多特色菜了。