可以在SQL中定义函数,按一定的格式查找出数据
如下 将在团组表中按(团组名称:人数/团组名称:人数...)这种格式查出属于于某个班级下的所在团组名称与人数
CREATE FUNCTION [dbo].[GetOrgNameAndTraineeNos]
(
-- Add the parameters for the function here
@ClassID varchar(50)
)
RETURNS varchar(4000)
AS
BEGIN
declare @VarName varchar(8000)
set @VarName = ''
select @VarName = @VarName + '/' + OrgName + ':' + convert(varchar,TraineeNo) + '人'
from dbo.ClassOrganization
where ClassID = @ClassID
if(len(@VarName) >0)
set @VarName = substring(@VarName,2,len(@VarName)-1)
return @VarName
END
正确的调用 如下:
begin WITH list AS
( SELECT ROW_NUMBER() OVER (ORDER BY cb.ClassID DESC)AS Row,cb.* FROM //要将行号与选择的内容提到最外面层
( SELECT c.ClassID,c.CLASSNO,c.ProgramName,
c.ClassType,m.ItemName, c.TraineeNo,c.StartDate,c.EndDate,c.Days,c.FromNo,
c.AttendNo,c.WithNo,c.ClassRoom,c.Receptionist,c.Remark,c.ColName1,
dbo.GetOrgNameAndTraineeNos(c.ClassID) as OrgNameAndTraineeNo //调用 函数
from ClassBasic c join MD_MainCodeDetail m on c.ClassType=m.ItemCode ) cb //重命名选择出的内容为临时表
WHERE 1=1 And cb.ColName1='1' And cb.ClassNo like '%10OSSZCLC002%' ) //条件属于临时表cb
SELECT * FROM list WHERE Row between 1 and 1
end