在SQL存储过程中使用Cursor来调用另一个存储过程

时间:2017-12-18 13:56:06

标签: sql-server stored-procedures cursor

以下过程应该获取存储在VisitorFunctions表中的所有过程。目前,它只是为表中的最后一个条目提取和执行。

我已经使用了光标作为选项,但似乎无法正常工作

ALTER PROCEDURE [dbo].[Visit]
    @visitPoint nvarchar(100),
    @recordType nvarchar(100),
    @id int,
    @username nvarchar(56)
AS
BEGIN
    SET NOCOUNT ON;

    -- TODO: Do we need to support multiple visitors (e.g. School and Asset?)
    declare @typeSpName nvarchar(100)
    declare @spName nvarchar(100)
    select @spName = v.StoredProcedure from VisitorFunctions v join VisitPoints vp on vp.Id = v.VisitPointId where vp.Name = @visitPoint and v.RecordType = @recordType

    -- if SemanticWeb then get the node type
    if @spName is not null and @recordType = 'SemanticWeb'
    begin
        ;with recurSet(parentId)
        as
        (
            select templateId
            from sw.CoreData
            where ID = @id

            union all

            select p.parentId
            from sw.Template p
            join recurSet rs on rs.parentId = p.ID
            where p.ParentID is not null
        )

        select @typeSpName = v.StoredProcedure 
        from recurSet rs
        join VisitorFunctions v on v.SemanticWebNodeTemplateId = rs.parentId and v.RecordType = @recordType
        join VisitPoints vp on vp.Id = v.VisitPointId and vp.Name = @visitPoint

        if @typeSpName is not null
        begin
            set @spName = @typeSpName
        end
        else
        begin
            set @spName = null
        end
    end

    -- call it
    if @spName is not null
    begin
        declare @sql nvarchar(max) = @spName + ' ''' + @recordType + ''', ' + cast(@id as nvarchar) + ', ''' + @username + ''''
        exec sp_executesql @sql
    end
END

0 个答案:

没有答案