代码之家  ›  专栏  ›  技术社区  ›  adopilot

SQL选择打印出存储过程的结果

  •  2
  • adopilot  · 技术社区  · 14 年前

    我的业务应用程序只支持使用SQL Server中选定的数据进行报告。在一个业务流程中,我有一个非常复杂的存储过程,它使用其他存储过程,旨在将结果打印为作业完成日志。我想要捕捉打印出来的内容,并将其选为varchar(max),这样我的应用程序就可以处理这些数据并将其显示给用户。
    下面是TSQL代码中描述的示例场景:

    create procedure sp_test_print_out
    as
    begin
        Print 'Test';
        print 'Test 1';
    end
    go
    
    create procedure sp_test_print_out_to_select
    as 
    declare @printOut varchar(max)
    set @printOut = exec sp_test_print_out --How I can achieve this ?
    select @printOut
    end
    
    go
    
    exec sp_test_print_out_to_select
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Thakur    14 年前

    您可以尝试在输出参数中设置值

    create procedure sp_test_print_out
    @printMessages varchar(max) output
    as
    begin
    set @printMessages='Test'
    Print 'Test';
    
    set @printMessages= @printMessages + CHAR(10)
    set @printMessages= @printMessages + 'Test 1'
    print 'Test 1';
    end
    go
    
    
    create procedure sp_test_print_out_to_select
    as 
    begin
    declare @printOut varchar(max)
    exec sp_test_print_out @printOut output -- can be achieved using output parameter ?
    select @printOut
    end
    
    go
    
    exec sp_test_print_out_to_select
    
        2
  •  0
  •   adopilot    14 年前

    还有一种从存储过程中的打印命令中获取所选数据的粗略方法,可能是错误的。

    命令 xp_cmdshell sqlcmd 能胜任这项工作。由于安全原因,xp_cmdshell大部分被禁用,不允许在大多数SQL服务器上使用。

    下面是代码:

    CREATE TABLE #temp
    (OUTPUT VARCHAR(MAX));
    
        declare @cmd varchar(800);
        set  @cmd = 'sqlcmd -d RobotTest -Q "exec sp_test_print_out"';
    
        INSERT INTO #TEMP
        exec xp_cmdshell @cmd  ;
    
    select output from #temp;
    drop table #temp;