日期:2014-05-18  浏览次数:20580 次

怎么在sql 2005下,自定义函数怎么输出table呢?
怎么在sql 2005下,自定义函数怎么输出table呢?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION GetChildId
(
-- Add the parameters for the function here
@ClassId int
)
RETURNS TABLE
AS
begin
 Select * From Class where ParentId =@ClassId 
end

错误:
消息 156,级别 15,状态 1,过程 GetChildId,第 13 行
关键字 'Select' 附近有语法错误。




------解决方案--------------------
SQL code
--函数参考:
带符号合并行列转换(爱新觉罗.毓华 2007-11-19于海南三亚)

有表tb,其数据如下:
  a b
  1 1
  1 2
  1 3
  2 1
  2 2
  3 1
如何转换成如下结果:
  a b
  1 1,2,3
  2 1,2
  3 1 
*/

create table tb
(
   a int,
   b int
)
insert into tb(a,b) values(1,1)
insert into tb(a,b) values(1,2)
insert into tb(a,b) values(1,3)
insert into tb(a,b) values(2,1)
insert into tb(a,b) values(2,2)
insert into tb(a,b) values(3,1)
go

--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
  declare @str varchar(8000)
  set @str = ''
  select @str = @str + ',' + cast(b as varchar) from tb where a = @a 
  set @str = right(@str , len(@str) - 1)
  return(@str)
End
go

--调用自定义函数得到结果:
select distinct a ,dbo.f_hb(a) as b from tb

drop table tb
drop function f_hb

/*
结果
a           b     
----------- ------
1           1,2,3
2           1,2
3           1

(所影响的行数为 3 行)
*/

----------------------------------------------------