BookmarkSubscribeRSS Feed
sasuser_221
Calcite | Level 5

I'm trying to truncate the variable length to 30 and compare with another variable in the same query. 

can you help me with the below 2 questions.

 

1. How to reuse the formatted variable in the query

2. How to limit the length of variable in the case when statement.

 

 

proc sql;
create table data1 as select

NAME length =30 as name_formatted,
case when name_formatted = name_2 then 'true' else 'false'

from table 1 a

;
quit;

 

 

4 REPLIES 4
PGStats
Opal | Level 21
proc sql;
create table data1 as 
select
	substr(NAME,1,30) as name_formatted length=30,
	case when calculated name_formatted = name_2 then 'true' else 'false' end as test
from table1;
quit;
PG
Tom
Super User Tom
Super User

You don't have any "formatted" variables, you aren't attaching formats to either of the two variables you are calculating.

Did you mean a CALCULATED variable?

Use the CALCULATED keyword to let the parser know that you are referring to a variable that was derived earlier in the list of columns being selected.

create table data1 as 
  select
    NAME length =30 as name_formatted
  , case when CALCULATED name_formatted = name_2 then 'true'
         else 'false' 
    end as flag
from table1 a
;

 

PGStats
Opal | Level 21

Unfortunately, @Tom , the SQL interpreter doesn't consider a change of string length as a "calculation". Some function (such as substr) or operator must be involved for a new column name to be considered as CALCULATED :

 

 71         proc sql;
 72         select
 73         name length=2 as nm,
 74         case when calculated nm = "Ja" then "True" else "False" end as flag
 75         from sashelp.class;
 ERROR: The following columns were not found as CALCULATED references in the immediate query: nm.
 NOTE: PROC SQL set option NOEXEC and will continue to check the syntax of statements.
 76         quit;
 NOTE: The SAS System stopped processing this step because of errors.
PG
Tom
Super User Tom
Super User

That is clearly a BUG. A change in name should be enough to require/allow the use of the CALCULATED keyword.

 

Given that limitation of PROC SQL you should use the SUBSTR() , or perhaps better the SUBSTRN() function to make sure it thinks you are calculating something.  

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 887 views
  • 0 likes
  • 3 in conversation