如何在SQL Server中为以下场景创建函数

时间:2017-02-20 18:16:21

标签: tsql sql-server-2012

我需要创建一个返回字符串的函数。函数输入为studentid

select * 
from StudentReference
where studentid = ?
order by Subid 

表格格式如下:

studentid  subname    subid 
------------------------------
1          math         2
1          sci,xx       3
1          social       1  

函数输入为studentid,如上所述,它应按subid排序,函数应返回字符串social~math~sci,xx

任何人都可以提出想法吗?

select 
    T1.studentid,
    stuff((select '~' + T2.subname
           from Studenttable as T2
           where T1.studentid = T2.studentid
           for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as subname
from 
    Studenttable as T1
group by 
    T1.studentid   

如何通过函数中的subid将上述逻辑转换为studentntid作为表顺序的i / p?

0 个答案:

没有答案