gpt4 book ai didi

regex - SAS 在开始或结束表达式时删除指定的单词

转载 作者:行者123 更新时间:2023-12-01 11:31:07 25 4
gpt4 key购买 nike

我正在编写一个宏变量,旨在生成用户在提示中指定的有效 SQL WHERE 子句。假设我们有 3 个变量 X、Y、Z 等。用户可以为每个变量和宏变量指定过滤器,如下所示:

a = x eq 1 and y eq 1 and z eq 1;

然后进入 WHERE 子句。但是,如果用户仅指定,假设“Y 过滤器”看起来像:

a =  and y eq 1 and 

我希望它看起来像:

a = y eq 1

这就是为什么我想在开始或结束表达式时以某种方式删除操作数“AND”(它可能多次开始或结束它,例如,如果我们只安装 Z 变量,它看起来像):

a =  and and and z eq 1 

我想这可以用正则表达式轻松完成,但由于我是新手,有没有人愿意帮助我? ;)

最佳答案

对@DirkHorsten 的技术进行了轻微修改。这只是以稍微不同的方式组织代码,以便可以更轻松地阅读 SQL 语句。在我看来,SQL 语句是您希望读者理解的重要代码片段(因此让我们保持简单!),而 where 子句的构建只是旁注。这是一种有值(value)的方法,尤其是当您的 SQL 语句变得更加复杂时。

方法 1,所有过滤器的单个变量:

%macro getMyData(xValue=, yValue=, zValue=);
%local and_filters;

* THE BORING IMPLEMENTATION DETAILS ARE KEPT SEPARATE;
%let and_filters = ;
%if "&xValue" ne "" %then %do;
%let and_filters = &and_filters and sex eq "&xValue";
%end;
%if "&yValue" ne "" %then %do;
%let and_filters = &and_filters and age eq &yValue;
%end;
%if "&zValue" ne "" %then %do;
%let and_filters = &and_filters and height eq &zValue;
%end;

* THE IMPORTANT PIECE OF CODE IS EASY TO READ;
proc sql;
select *
from sashelp.class
where 1 &and_filters
;
quit;
%mend;

方法 2,每个过滤器的单独变量:

%macro getMyData(xValue=, yValue=, zValue=);
%local and_sex_filter and_age_filter and_height_filter;

* THE BORING IMPLEMENTATION DETAILS ARE KEPT SEPARATE;
%let and_sex_filter = ;
%let and_age_filter = ;
%let and_height_filter = ;

%if "&xValue" ne "" %then %do;
%let and_sex_filter = and sex eq "&xValue";
%end;
%if "&yValue" ne "" %then %do;
%let and_age_filter = and age eq &yValue;
%end;
%if "&zValue" ne "" %then %do;
%let and_height_filter = and height eq &zValue;
%end;

* THE IMPORTANT PIECE OF CODE IS EASY TO READ;
proc sql;
select *
from sashelp.class
where 1
&and_sex_filter
&and_age_filter
&and_height_filter
;
quit;
%mend;

关于regex - SAS 在开始或结束表达式时删除指定的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31856652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com