2013-03-29 201 views
0

对于关于以下文章,我有一个问题,我会添加到它,但它不会让我,因为我是新的。将函数值合并为一个字符串的sql函数

Link Here

编辑添加的特定类型的表,更好的信息

我有下面两个表,并希望在获得studentname的tblnames到tblCombineNames到学生名字的完成。

请指教,谢谢!

TblNames

ID(PK)   StudentType(FK) StudentNo(FK) GradeNo(FK)  StudentName 
----------  ----------  ----------  ----------  ------------- 
1    1    1    1    Mary   
2    1    1    1    John   
3    1    1    1    Sam   
4    2    2    2    Alaina  
5    2    2    2    Edward  
6    2    2    2    Joe   

我想输出要低于

TblCombineNames

ID(PK)   StudentType(PK) StudentNo(PK) GradeNo(PK)  StudentNames  
----------  ----------  ----------  ----------  -------------  
1    1    1    1    Mary, John, Sam  
2    2    2    2    Alaina, Edward, Joe 

我想有一个标量值函数名字类似

---dbo.fn_Concatenate_Names 
ALTER FUNCTION [dbo].[fn_Concatenate_Names] 
(
    @StudentType VARCHAR(250), 
    @StudentNo VARCHAR(250), 
    @GradeNo VARCHAR(250) 
) 
RETURNS Varchar(250) 
BEGIN 
Declare @rtn Varchar(250) 

BEGIN 
    Select @rtn=(
    Select StudentNames + ', ' as 'data()' 
    from tblStudentnames  
    where studentType = @StudentType and StudentNo = @StudentNo and GradeNo = @GradeNo 
    for XML path('') 
    ) 

    Set @rtn = LEFT(@rtn, Len(@rtn) - 1) 
    END 
    RETURN (@rtn) 
END 

我会做更新想调用的函数

update tblCombineNames 
set studentnames = fn_concatenate_names(StudentType,StudentNo,GradeNo) 

看起来这会工作,但它需要2个小时到的250730条记录tblStudentNames运行。我不认为这会持续很长时间。

+0

? Postgres的?甲骨文? –

+0

对不起,我是SQL 2008 – eripey

+0

[这里的帖子越来越接近了,我需要弄清楚如何在函数中使用它。点击查看我在说的帖子。](http://stackoverflow.com/questions/11890590/if-countvalues-1-combine-all-values-into-a-single-cell) – eripey

回答

1

你可以简单地把它的子查询中,并与表JOIN它,当然

UPDATE a 
SET  a.names = b.StudentsList 
FROM tableName a 
     INNER JOIN 
     (
      SELECT ST2.SubjectID, 
        substring((SELECT ','+ ST1.StudentName 
          FROM dbo.Students ST1 
          WHERE ST1.SubjectID = ST2.SubjectID 
          ORDER BY ST1.SubjectID 
          For XML PATH ('')),2, 1000 
          ) StudentsList 
      FROM dbo.Students ST2 
      GROUP BY ST2.SubjectID 
     ) b ON a.SubjectID = b.SubjectID 
WHERE a.SubjectID = @subjectid 
您使用哪种DBMS
+0

J W,你可以看看我原来的帖子,我已经包含了表格来给出一个更好的例子。为什么更新花费这么长时间,我对此感到迷茫。 – eripey

+0

你有索引设置列专题ID吗? –

+0

我不确定你是什么意思,如果你的意思是进入桌子设计,是的可转位,是的。 您是否介意再次查看我的帖子,我编辑后张贴更有用的东西,可能会更有意义,请告知,谢谢! – eripey