使用填充函数输出一行

时间:2010-06-09 10:02:47

标签: sql-server

我想要的是一排, 虽然我试图使用cast功能,但没有太大的成功。有人能告诉我如何实现这个MS SQL服务器,就像在oracle中我们有一些功能,如stragg

我得到以下结果:

Tenancy No Property NO usercode name       Address   person no  lead tenant
123    1234        12345 MR  Rose   Temp add  1          1  
123    1234        12345 MRS Rose   Temp add  2          0

但我想要这样的事情:

123    1234        12345 MR  Rose ; MRS ROSE   Temp add  1 ; 0  

这是我的代码:

Select   distinct(t."prhst-occ-num") as "TENANCY_REF",         
  per."pr-seq-no"   as "PROPERTY-REF-NO" ,         
  pr."user-cde"     as "USER_CDE",         
  **/*CAST( SUBSTRING( stuff ((
   select distinct(',' + per."fnam")
   From   per per ,
                prhst  prh,
                aTNCY   t 
   where  prh."per-num"=per."num"
   and  t."prhst-occ-num"=prh."occ-num"  
   and  prh."lead-tenant" in (0,1)
   for XML Path('')
   ), 1, 1, ''),1,500) as nvarchar(500)) as "FIRSTNAMES",*/**

         per."fnam" + '-' + per."snam"  as "FULL NAME",  
         pr."addr" + ' '+ pr."postcode"     as  "FULL ADDRESS" ,
         prh."tenu-cde",
  prh."per-num"                 as  "PERSON NUMBER",
  prh."lead-tenant"        as  "LEAD TENANT"   ,
From     TNCY   t, 
         PR     pr,   
         PRHST  prh,
         per    per  
Where    t."prhst-occ-num"=prh."occ-num"
  and    pr."seq-no"=prh."pr-seq-no"
  and    per."num"=prh."per-num"
order by 1,2

1 个答案:

答案 0 :(得分:0)

所以你想将多行压缩成一个文本列。 for xml子句可以执行此操作,但通常将其应用于子查询。例如:

select  TextColumn + ';' as [text()]
from    (
        select FirstName + ' ' + LastName as TextColumn
        from Customers
        ) sub
for xml path('')

如果输入带有名称的表,则此查询将打印一行:

Jeffrey Jones;Andrei Voronkov;George Boole;Kurt Gödel

您可以将子查询替换为任何其他查询,例如:

select  TextColumn + ';' as [text()]
from    (
        select  t.[prhst-occ-num] + ' ' + per.fnam + '-' + 
                    per.snam as TextColumn
        from    TNCY   t, 
                PR     pr,   
                .....
        order by
                t.[prhst-occ-num]
        ) sub
for xml path('')