首页 > 解决方案 > SAS 连接到 SQL Server 并返回参数

问题描述

我想将 SQL Server 存储过程的返回值保存在 SAS 变量中。

这是我的代码:

proc sql;
Connect To OLEDB As MyDb ( Init_String = "  Provider=SQLOLEDB.1; ... )

    Execute (spDamjanTest) by MyDb;

    Disconnect From MyDb;
Quit;

如果我使用下面的代码,存储过程会执行两次:

     proc sql; 
            connect to oledb as SQLSVR (provider=sqloledb
            properties=("Data Source"=...);
            select *
            from connection to SQLSVR
            (exec spDamjanTest);
            disconnect from SQLSVR;
    quit;

存储过程:

 CREATE PROCEDURE spDamjanTest
  AS
  Select 5

标签: sql-serversas

解决方案


SQL Server 存储过程的表输出(我们称之为结果集)可以通过insert将其写入临时表来捕获。一旦结果集位于临时 ( #<table-name>) 表中,您就可以从 SAS 中进行选择。

* libname SS sqlsvr ... ;

proc sql;
  connect using SS;

  execute (
    create table #sp_table_out (
      column1 int
    )
    insert into #sp_table_out exec dbo.spDamjanTest
  ) by SS;

  create table work.sp_output as
  select * from connection to SS
  (
    select * from #sp_table_out 
  );

  execute (
    drop table #sp_table_out
  ) by SS;
quit;

proc print data=work.sp_output;
run;

此答案基于How to Get the Output of a Stored Procedure into a Table Greg Larsen,2016 年 11 月中的信息


推荐阅读