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