读书人

创造Funtion函数

发布时间: 2013-06-19 10:26:41 作者: rapoo

创建Funtion函数
以下代码,我想放到function中,怎么实现,在调用function时,不能够传递参数。
该Function作用,循环向表 "tmp_DeptTB"中插入数据,最后select,返回结果集,怎么搞.


declare @totalcount int,
@rownum int,
@id varchar(10),
@deptName varchar(100),
@sql varchar(max),
@guid varchar(100),
@temp varchar(10)
select @totalcount=count(1) from (select distinct t3.ID,t3.DeptName,t3.RootPath from PMProject t1
left join PMProjectSalesInfo t2 on t2.ProjectID=t1.ID
join SCDepartment t3 on t2.SalesInfoDeptID=t3.ID
where t1.ProjectStateID=3 )a
set @rownum=1
set @id=0
set @sql=''
select @guid= newid()
while @rownum <= @totalcount
begin
select top 1 @id=tb1.ID,@deptName=tb1.DeptName from ( select distinct t3.ID,t3.DeptName,t3.RootPath from PMProject t1
left join PMProjectSalesInfo t2 on t2.ProjectID=t1.ID
join SCDepartment t3 on t2.SalesInfoDeptID=t3.ID
where t1.ProjectStateID=3) tb1 where tb1.ID > @id order by tb1.ID
if( select PATINDEX('%14%',t1.RootPath) from SCDepartment t1 where ID= @id)>0
begin
if(select PATINDEX('%14,%',t2.RootPath) from SCDepartment t2 where ID= @id )>1
begin
insert into tmp_DeptTB(GUID,DeptID,ParentID,DeptName,RootPath) select @guid 'Guid',ID 'DeptID' ,ParentID,DeptName,RootPath from SCDepartment t1 where t1.ID=( select SUBSTRING(substring(t1.RootPath,10,100),0, PATINDEX('%,%',substring(t1.RootPath,10,100))) from SCDepartment t1 where ID=@id)
end
else
begin
insert into tmp_DeptTB(GUID,DeptID,ParentID,DeptName,RootPath) select @guid 'Guid',ID 'DeptID',ParentID,DeptName,RootPath from SCDepartment t3 where IsOn=1 and ID=@id
end
end
else
begin
insert into tmp_DeptTB(GUID,DeptID,ParentID,DeptName,RootPath) select @guid 'Guid',ID 'DeptID',ParentID,DeptName,RootPath from SCDepartment where ID=(select t1.ParentID From SCDepartment t1 where t1.ID=@id)
end
set @rownum=@rownum+1
end
select * From tmp_DeptTB
SQL 函数
[解决办法]
看一下exec procname 结果是几列的,先创建一个临时表。

把exec的结果插入临时表就可以了。

参考:http://www.cnblogs.com/JohnXIe/archive/2008/04/24/1169722.html
------解决方案--------------------


把表tmp_DeptTB定义成表变量
[解决办法]
CREATE FUNCTION ff(
@totalcount int,
@rownum int,
@id varchar(10),
@deptName varchar(100),
@sql varchar(max),
@guid varchar(100),
@temp varchar(10)
)
RETURNS @tmp_DeptTB TABLE
(
/*
表结构
*/
)
AS
BEGIN
/*你的语句*/
RETURN
END

另外function里面不能使用 newid

读书人网 >SQL Server

热点推荐