SQL 存储过程 :根据ID获取不包含自身和子项的项目

USE [PrettyCloud]
GO
/****** Object:  StoredProcedure [dbo].[GetParentLevel]    Script Date: 04/20/2018 14:30:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/**
功能:根据ID获取不包含自身和子项的项目
**/
ALTER Procedure [dbo].[GetParentLevel]
    @TableName    varchar(50)='',  --表名
    @Id            varchar(50)='',      --ID
    @Tj            varchar(50)='',   --关键字
    @Sx         varchar(50)=''      --条件
as
begin
    declare @mainSql  varchar(max)
    if @Id is null
    begin
        set @Id=''
    end
    set @mainSql='With org '    
    set @mainSql=@mainSql+' as '    
    set @mainSql=@mainSql+'('    
    set @mainSql=@mainSql+' select * from '+@TableName+' where Id='''+@Id+''''
    set @mainSql=@mainSql+' Union all '
    set @mainSql=@mainSql+' select '+@TableName+'.* from org '    
    set @mainSql=@mainSql+' join '+@TableName
    set @mainSql=@mainSql+' on org.Id='+@TableName+'.ParentId '
    set @mainSql=@mainSql+')'    
    
    set @mainSql=@mainSql+' select * from '+@TableName+' o '
    set @mainSql=@mainSql+' where o.DeleteMark is null and not exists  '    
    set @mainSql=@mainSql+'('    
    set @mainSql=@mainSql+'select id from org where Id=o.Id'
    set @mainSql=@mainSql+') order by '+@Tj+' '+@Sx+' '    
    print @mainSql
    execute (@mainSql)
end

 

posted @ 2018-04-20 14:31  莫小麦  阅读(431)  评论(0编辑  收藏  举报