2015-10-19 55 views
-1

我有两个表ProceduresProcedureTypesSQL Server 2012中的简单拆分功能与解释请参阅

Procedures具有柱Type其是与值的VARCHAR(1,2),(3,4),(4,5)等...

ProcedureType具有主键 'ID' 1至9

ID Description 
1 Drug 
2 Other-Drug 
etc... 

IDinteger值和Typevarchar值。

现在我需要连接这两个表显示的值

  • IDProcedures
  • ProcedureTypeProcedures
  • ProceduresType表被分隔值Description“ - ”。

例如,如果他类型值后(1,2)的新表连接应显示在像(药等药物)说明值

我已经使用这个查询机器人无济于事

SELECT * FROM DBO。[SPLIT]((选择GPsProcedures请求类型), '')

谁能告诉我该怎么做,为什么上面的查询工作不

+1

你有没有尝试过任何@LitaSheelkumar? –

+2

理想情况下,更改桌子的设计。在一个理智的数据库中,每列应该包含一个标量值(每行)。表是用于保存多个值(作为行)的*数据类型。 –

+0

每列类型的最大数量是多少? –

回答

0
with Procedures as (
select 1 as ID, '1,2,3' as Typ 
), 
ProcedureTypes as (
    select 1 as TypeID, 'Drug' as Name 
    union select 2 , 'Other-Drug' 
    union select 3 , 'Test 3' 
) 
/*Get one extra column of type xml*/ 
,Procedures_xml as (
    select id,CONVERT(xml,' <root> <s>' + REPLACE(Typ,',','</s> <s>') + '</s> </root> ') as Typ_xml 
    from Procedures 
) 
/*Convert the field string to multiple rows then join to procedure types*/ 
, Procdure_With_Type as (
select ID,T.c.value('.','varchar(20)') as TypeID, 
     ProcedureTypes.Name 
     from Procedures_xml 
CROSS APPLY Typ_xml.nodes('/root/s') T(c) 
INNER JOIN ProcedureTypes ON T.c.value('.','varchar(20)') = ProcedureTypes.TypeID 
) 
/*Finally, group the procedures type names by procedure id*/ 
select id, 
    STUFF((
    SELECT ', ' + [Name] 
    FROM Procdure_With_Type inn 
     WHERE (Procdure_With_Type.ID = inn.ID) 
     FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)') 
     ,1,2,'') AS NameValues 
from Procdure_With_Type 
group by ID 
+0

这是一个很好的例子,但是你能告诉我为什么这种方式不起作用吗? SELECT * FROM dbo。[Split]((从GPsProcedures中选择RequestType),',') –

0

你不能有一个select语句作为一个函数的参数,所以不是这样的:

SELECT * FROM dbo.[Split]((select RequestType from GPsProcedures), ',') 

使用此:

select S.* 
from GPsProcedures P 
cross apply dbo.[Split](P.RequestType, ',') S 
+0

即时获取错误:'。'附近语法不正确。 –