%macro 中的 SAS proc sql [英] SAS proc sql inside %macro

查看:34
本文介绍了%macro 中的 SAS proc sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我有下表:

data dataset;
    input id $ value;
    datalines;
    A 1
    A 2
    A 3
    A 4
    B 2
    B 3
    B 4
    B 5
    C 2
    C 4
    C 6
    C 8
    ;
run;

我想编写一个宏,以便用户可以通过提供 id 值来对数据进行子集化.我在宏中执行 proc sql 如下:

I would like to write a macro so that the user can subset the data by giving the id value. I do proc sql inside the macro as follows:

%macro sqlgrp(id=,);

proc sql;
        create table output_&id. as
        select *
        from dataset
        where id = '&id.'
        ;
    quit;
%mend;

%sqlgrp(id=A); /*select id=A only*/

我能够在 WORK 库中生成 output_A 表,但是它有零 (0) 个观察值.

I am able to generate the output_A table in the WORK library, however it has zero (0) observations.

为什么这不起作用?

推荐答案

引用宏变量时需要使用双引号.

You need to use double quotes when referring to macro variables.

当前代码

%macro sqlgrp(id=,);

proc sql;
        create table output_&id. as
        select *
        from dataset
        where id = '&id.'
        ;
    quit;
%mend;

%sqlgrp(id=A); /*select id=A only*/

查找 id字面&id."值.您可以通过创建此数据集来测试这一点:

Looks for values of id that are literally '&id.'. You can test this by creating this dataset:

data dataset;
    input id $ value;
    datalines;
&id. 2
A    2
    ;
run;

现在,使用%let来设置宏变量id的值:

Now, use %let to set the value of the macro variable id:

%let id=A;

快速测试单引号和双引号之间的功能差异.请注意,标题还包含单引号和双引号,因此我们可以确切地看到输出中发生了什么:

Run a quick test of the functionality difference between single and double quotes. Notice the titles also contain single and double quotes, so we can see exactly what has happened in the output:

proc sql;
  title 'Single Quotes - where id=&id.';
  select *
  from dataset
  where id='&id.';

  title "Double Quotes - where id=&id.";
  select *
  from dataset
  where id="&id.";
  title;
quit;

正确的代码

%macro sqlgrp(id=,);

proc sql;
        create table output_&id. as
        select *
        from dataset
        where id = "&id."
        ;
    quit;
%mend;

%sqlgrp(id=A); /*select id=A only*/

双引号允许宏变量 &id 解析为A",这将根据您的输入返回结果.

The double quotes allow the macro variable &id to resolve to 'A', which will return results based on your input.

这篇关于%macro 中的 SAS proc sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆