日期:2014-05-17 浏览次数:20660 次
--实现split功能 的函数
create function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10))
returns @temp table(a varchar(100))
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>'\'
insert @temp values(@SourceSql)
return
end
go
--测试数据
CREATE TABLE t_A
(ID int,name VARCHAR(200),ParentID int)
INSERT INTO t_A
SELECT 1,'aa',0
UNION ALL
SELECT 2,'bb',0
UNION ALL
SELECT 3,'cc',1
UNION ALL
SELECT 4,'dd',3
go
--求个节点下所有子节点:
create function f_cid(@id int)
returns varchar(500)
as
begin
declare @t table(id int,desn varchar(10),parentid int ,lev int)
declare @lev int
set @lev=1
insert into @t select *,@lev from t_A where id=@id
while(@@rowcount>0)
begin
set @lev=@lev+1
insert into @t select a.*,@lev from t_A a,@t b
where a.parentid=b.id and b.lev=@lev-1
end
declare @cids varchar(500)
select @cids=isnull(@cids+'-','')+ltrim(id) from @t order by lev
return @cids
end
go
select *,dbo.f_cid(id) as jd from t_A
--删除数据
declare @var varchar(500)
select @var=dbo.f_cid(id) from t_A where id = 1--参数1
delete from t_A where id in (
select a.id from t_A a ,dbo.f_split(@var,'-') b
where a.id =b.a )
select * from t_A
--drop table t_A
--DROP FUNCTION dbo.f_cid
--DROP FUNCTION dbo