Using column number inplace of column name in SQL Select statement
Is there a way to run sql select statements with column numbers in
place of column names?
Current SQL
select AddressId,Name,City from AddressIs this possible
select 1,2,5 from AddressThanks in Advance
user10962462 wrote:
well, ok, it's not possible with SQL, but how about PL/SQL?As mentioned, using DBMS_SQL you can only really use positional notation... and you can also use those positions to get the other information such as what the column is called, what it's datatype is etc.
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
v_v_val VARCHAR2(4000);
v_n_val NUMBER;
v_d_val DATE;
v_ret NUMBER;
c NUMBER;
d NUMBER;
col_cnt INTEGER;
f BOOLEAN;
rec_tab DBMS_SQL.DESC_TAB;
col_num NUMBER;
v_rowcount NUMBER := 0;
BEGIN
-- create a cursor
c := DBMS_SQL.OPEN_CURSOR;
-- parse the SQL statement into the cursor
DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
-- execute the cursor
d := DBMS_SQL.EXECUTE(c);
-- Describe the columns returned by the SQL statement
DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
-- Bind local return variables to the various columns based on their types
FOR j in 1..col_cnt
LOOP
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val); -- Number
WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val); -- Date
ELSE
DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Any other type return as varchar2
END CASE;
END LOOP;
-- Display what columns are being returned...
DBMS_OUTPUT.PUT_LINE('-- Columns --');
FOR j in 1..col_cnt
LOOP
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
when 2 then 'NUMBER'
when 12 then 'DATE'
else 'Other' end);
END LOOP;
DBMS_OUTPUT.PUT_LINE('-------------');
-- This part outputs the DATA
LOOP
-- Fetch a row of data through the cursor
v_ret := DBMS_SQL.FETCH_ROWS(c);
-- Exit when no more rows
EXIT WHEN v_ret = 0;
v_rowcount := v_rowcount + 1;
DBMS_OUTPUT.PUT_LINE('Row: '||v_rowcount);
DBMS_OUTPUT.PUT_LINE('--------------');
-- Fetch the value of each column from the row
FOR j in 1..col_cnt
LOOP
-- Fetch each column into the correct data type based on the description of the column
CASE rec_tab(j).col_type
WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_n_val);
WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
ELSE
DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
END CASE;
END LOOP;
DBMS_OUTPUT.PUT_LINE('--------------');
END LOOP;
-- Close the cursor now we have finished with it
DBMS_SQL.CLOSE_CURSOR(c);
END;
SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
DEPTNO - NUMBER
SAL - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
DEPTNO : 10
SAL : 2450
Row: 2
EMPNO : 7839
ENAME : KING
DEPTNO : 10
SAL : 5000
Row: 3
EMPNO : 7934
ENAME : MILLER
DEPTNO : 10
SAL : 1300
PL/SQL procedure successfully completed.
SQL> exec run_query('select * from emp where deptno = 10');
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
JOB - VARCHAR2
MGR - NUMBER
HIREDATE - DATE
SAL - NUMBER
COMM - NUMBER
DEPTNO - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
JOB : MANAGER
MGR : 7839
HIREDATE : 09/06/1981 00:00:00
SAL : 2450
COMM :
DEPTNO : 10
Row: 2
EMPNO : 7839
ENAME : KING
JOB : PRESIDENT
MGR :
HIREDATE : 17/11/1981 00:00:00
SAL : 5000
COMM :
DEPTNO : 10
Row: 3
EMPNO : 7934
ENAME : MILLER
JOB : CLERK
MGR : 7782
HIREDATE : 23/01/1982 00:00:00
SAL : 1300
COMM :
DEPTNO : 10
PL/SQL procedure successfully completed.
SQL> exec run_query('select * from dept where deptno = 10');
-- Columns --
DEPTNO - NUMBER
DNAME - VARCHAR2
LOC - VARCHAR2
Row: 1
DEPTNO : 10
DNAME : ACCOUNTING
LOC : NEW YORK
PL/SQL procedure successfully completed.
SQL>
Similar Messages
-
How can i pass a variable instead of a table name in the Select statement.
Dear all
how can i pass a variable instead of a table name in a select statement ?
Example :-
Begin
P_get_procedure_tname (aap_name,otable_name);--It will take an application name and will return a table name
Select col1 into ocol1
from ---- here i want to pass the variable OTABLE_NAME
End;How can i pass this ?Hi,
You can use dynamic sql.
EXECUTE IMMEDIATE 'SELECT COL1 INTO ' || OCOL1 || ' FROM " || OTABLE_NAME;
{code}
cheers
VT -
How to use a table name in the select statement using a variable?
Hi Everybody,
I got a internal table which has a field or a variable that gets me some tables names. Now I need to retrieve the data from all these tables in that field dynamically at runtime. So could you suggest me a way out to use the select query which uses this variable as a table ?
Regards,
Mallik.Hi all,
Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
for ex : select * from (tab_name) where....?
Can we do inner join on such select statements? If so how?
Thanks & Regards,
Mallik. -
Is there any way to Mask the Name when a select statement is issued?
Dear all,
Is there any way to mask the name .. i mean if User issue a select statement in a customer table the real name should come like ' ABCXXXDEFXXCFXX'... Which is not the actual name?
e.g if Name: CHIEV SONG MEE
If user issue a statment select * from customers;
The Result Should come something Like this:
Name
CHXXV SXNG MXX
Thank Youuser3029023 wrote:
but it seems there is no option in oracle it self which can be used as there they are saying to get a data masking software which we can't due to some internal issues....I would not say that. How one implements masking depends entirely on the requirements that need to be met.
For example, schema A owns all the tables. Schema B can be created as a "trusted" schema - in other words, schema A trusts schema B and allows it full access (with grants) to its tables. Schema B implements data masking as views. For each table in A, a view exists in B that implements the required masking. B can now grant select access on these views to user C. User C will see the same data object names in B as it would have if it used A - only, by using the B data objects it uses masked data objects and not the original source data objects.
Another example - schema Dev is to have all the data objects of schema Prod, but masked where needed. One can use CTAS (Create Table As Select) to create the required tables in Dev with masked values where relevant. This Dev schema can be "refreshed" on weekends by dropping all tables and getting a new fresh copy of production data and masking it - ready for the next week's development cycle.
If the application use is for example APEX, then instead of coding SQL directly as reporting regions to display, a function is used instead. APEX supports reporting regions where it calls a function and this function provides the APEX run-time with the SQL to execute and contents to render. It is easy to use this approach to implement logic in functions that masked column data depending on who the APEX user is, the security/role attributes of the user, and so on.
No there is not a single "+mask this column!+" feature in Oracle.. but that does not mean that such a feature is not supported and cannot be implemented. Oracle has a very comprehensive and rich set of tools - more so than most (if not all) other RDBMS products.
It is up to the architect/designer/developer to use this toolkit in creating a system that meets the specific requirements at hand. -
Create Dynamic table name in the select statement.
I use oracle reports 6i to make myrep.rdf , this report created using certain select query Q1, I created a formula column in this report,
in the formula column I write pl/sql block statements to select the data from certain table depends on the output of a column in Q1,
I want to make the pl/sql block dynamically enough to change the user which I select the data from depends on the connected user
Ex: if I connected with user = 'KAM14'
the pl/sql block will be
select x into v_value from kam13.bil_file where .....;
and if I connected with user = 'KAM13'
the pl/sql block will be
select x into v_value from kam12.bil_file where .....;
and so on
how can I do this in the pl/sql block ...
Thanks in Advance.I am not sure I understood properly, but I think you should create bil_file table under a different user and create synonyms under KAM1x users.
Regards -
How to use variables in an sql select statement.
Hi, I have seen examples using the update, but nothing using a select statement.
I have four variables I am getting from drop down menus in my JSP I set the user selected items to strings.
How would I create the select statement like this:
.String XName = request.getParameter("UserInputX");
rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = XName")Obviously it tries to read "XName" as a column and of course can't find it, how would I set it up to have it see the Value of XName and not the literal XName.read this:
rsInResult = stmtInResult.executeQuery("SELECT ColumxX FROM TableZ WHERE ColumnX = '"+XName+"')
{code}
better way is PreparedStatement:
{code}
// example code to change password to an user in the USERS table
String newPWD = "my password";
String user = "luxjava";
PreparedStatement prepStat;
String updatePWD = "UPDATE LOGISTIC.USERS "+
"SET logistic.users.password = ? "+
"WHERE logistic.users.username = ?";
prepStat = ql.conDb.prepareStatement(updatePWD);
prepStat.setString(1, newPwd);
prepStat.setString(2, user);
int zeroNotFound = prepStat.executeUpdate();
if (zeroNotFound==0)
ql.conDb.rollback();
prepStat.close();
else
ql.conDb.commit();
prepStat.close();
{code}
... use the SQLException to capture errors -
* table name in the select statements
Hi,
I have come across a select Statement as below.
Select * into *nast from nast where <conditions>.. End select.
what does this *nast represents and when is it used. why do we need to call a Table with *<Table Name>
Kind Regards,
Ushahi,
select statement will always points to a database table so we have to give database table name and it gets data from that table. for storing that data we have to use internal tables must have same structure of database table.
so select statement has the following form as........
select * from [dbtable] into table [internal table]
endselect.
in sap select will act as a loop so that we hav to use end sleect. select has different varities in sap. for some types no need of end select.
for ex:
select single *
select * ..................... into table [internal table name].....
if helpful reward some points.
with regards,
suresh. -
What is the use of additon in up to 1 rows in SELECT statement
Hi All,
What is the use of up to 1 rows in select statement.
for example
SELECT kostl
FROM pa0001
INTO y_lv_kostl UP TO 1 ROWS
WHERE pernr EQ pernr
AND endda GE sy-datum.
ENDSELECT.
I'm unable to get in wat situations we hav to add up to 1 rows
please help me out...
Thanks,
santosh.Hi,
Use "select up to 1 rows" only if you are sure that all the records returned will have the same value for the field(s) you are interested in. If not, you will be reading only the first record which matches the criteria, but may be the second or the third record has the value you are looking for.
The System test result showed that the variant Single * takes less time than Up to 1 rows as there is an additional level for COUNT STOP KEY for SELECT ENDSELECT UP TO 1 ROWS.
The 'SELECT .... UP TO 1 ROWS' statement is subtly different. The database selects all of the relevant records that are defined by the WHERE clause, applies any aggregate, ordering or grouping functions to them and then returns the first record of the result set.
Regards,
Bhaskar -
Usgent: using jsp date in sql select statement
i have something like this:
String day;
String month;
String year;
select * from event where date = xxx
where xxx is supposed to be obtained from the strings (day, month, year) and changed into a format that can be compared to in the select statement.
what should xxx be?
thks as lot cos i ahe been figuring out for very long.Use PreparedStatement and SimpleDateFormat:
String year = "2002";
String month = "9";
String day = "12";
String sDate = day + "/" + month + "/" + year;
SimpleDateFormat df = new SimpleDateFormat("M/d/yyyy");
Date dDate = df.parse(sDate);
Connection con = DriverManager.getConnection(user, pw);
PreparedStatement ps = con.prepareStatement("SELECT * FROM event WHERE date = ?");
ps.setDate(1, dDate);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
rs.close();
ps.close();
con.close(); -
Run time Column Name in the Select Statement
Hi there,
I face problem while writing sql statment for report in the Oracle reports.
The prom is I want to bound the where clause column name with the value stored in a variable e.g.
Select * from emp
where Column_Name = 'XYZ' ;
where the variable Column_Name have different values at different times, e.g.
At a time the value of Column_Name is Dept then
Select * from emp
where Dept = 'XYZ' ;
At other time value of Column_Name is City then
Select * from emp
where City = 'XYZ' ;
Waiting for the response .
Regards,
HafeezHi,
U can use lexical parameters for the solutions.U must be aware of it, but still i describe how to work it out.
1)In your datamodel in object navigator create a parameter under User parameter node.Name the parameter, for eg. p_clause.
set data type of parameter to character.
2)write a select query eg.
select * from emp &p_clause; --(THIS IS THE PARAMETER WE CREATED ABOVE)
3)Now run your report
Now in your parameter form pass the value for p_clause parameter.
eg: where name='JACK';
or
where city='NEWYORK';
or where deptno=10;
But do it in steps as above mentioned.
Do tell me if it works or not via mail on [email protected]
Enjoy.......
navneet jain
[email protected] -
Issue with Column Alias Name in a SELECT statement
I am trying to run sql query(IN ORACLE) to get the data from a remote database(TERADATA). The query is
select (table1.exp_date - table1.setup_date) AS day_diff,
CASE
WHEN day_diff = '0'
THEN 'YES'
WHEN day_diff > '0'
THEN 'NO'
ELSE 'Unknown'
END AS alias_type
from table1@remote_database_name;
The query is running fine when I run it in TERADATA environment directly without the remote database link since it is not necessary. If I run the above query in Oracle I am getting an error ORA-00904: invalid identifier.(this error is pointing to day_diff alias name)
Can anyone help me with this?
ThanksThe Column alias can be used in the ORDER BY clause, but not other clauses,like WHERE clause, in the query.
Use..
select (table1.exp_date - table1.setup_date) AS day_diff,
CASE
WHEN (table1.exp_date - table1.setup_date) = '0'
THEN 'YES'
WHEN (table1.exp_date - table1.setup_date) > '0'
THEN 'NO'
ELSE 'Unknown'
END AS alias_type -
Compare columns SQL select statement (easy question)
Hi,
I need to write a query which compares every account's products to see if they match up with a corresponding service. Here is an example of my dataset.
Account_no products service
0001 prod1, prod2,prod3 serv1, serv2,serv3
0002 prod1,prod2,prod4 serv1,serv2,serv3,serv4
0003 prod1,prod2 serv1,serv2
I would like to pick up either a service or a product that does not have a matching pair, so in this example it would pick up account_no 0002 and shoe me the products, services so I can see which one doesn't have a match.
Thanks in advance for any help.
Joeselect * from table_name
where to_number(replace(replace(replace(products,'prod',''),',',''),' ','')) <>
to_number(replace(replace(replace(services,'prod',''),',',''),' ','')); -
How to Get Top 10 records using SQL select statement.
:-) Hiee E'body,
I want to generate a sql report in which I only want the top 10 records based on the numeric value of a column.
For Example,
To generate a Location Wise, Employee Wise Years of Service Report.
Here I need the Top 10 Employees according to their No. of Years of Service for all the existing locations using a single query.
eg.
Location Emp No. YOS
India - 22 30
212 28
819 24 ...
US 123 40
312 33
90 33
144 30 ...
UK 77 20
79 20
331 18
109 16 ...
Every Location should display their respective Top 10 Employees
regarding their No. of Years of Service.
Please let me the know the solution to this.
Have a nice day.
Thanking You,
Vivek Kapoor.For example if the table contained (India rows only shown) :
India 202 30
India 212 28
India 819 24
India 820 24
India 900 20
India 920 18
India 922 17
India 925 16
India 926 15
India 927 14
India 928 13
India 929 13
India 930 12
do you want to see
India 202 30
India 212 28
India 819 24
India 820 24
India 900 20
India 920 18
India 922 17
India 925 16
India 926 15
India 927 14
or
India 202 30
India 212 28
India 819 24
India 820 24
India 900 20
India 920 18
India 922 17
India 925 16
India 926 15
India 927 14
India 928 13
India 929 13
Also if the India rows were
India 202 30
India 212 30
India 819 30
India 820 30
India 900 30
India 920 30
India 922 30
India 925 30
India 926 30
India 927 30
India 928 30
India 929 30
do you want to see
India 202 30
India 212 30
India 819 30
India 820 30
India 900 30
India 920 30
India 922 30
India 925 30
India 926 30
India 927 30
or
India 202 30
India 212 30
India 819 30
India 820 30
India 900 30
India 920 30
India 922 30
India 925 30
India 926 30
India 927 30
India 928 30
India 929 30
Please clarify.
Thanks,
Partha -
Restrict number of characters in table field for select statement.
SELECT * FROM table
WHERE column1 = z-column.
The field column1 is of type char and size 20
The field z-column is of type char size 10.
how do we perform this select?
Anyone can guide me?
Edited by: Hadesfx on Sep 11, 2009 3:56 PM
Edited by: Hadesfx on Sep 11, 2009 3:59 PMHello,
In your OP did you mention this? Please be specific when you post the next time.
Can you please post your code?
I think you have to try a work around:
DATA:
RS_STOCKID TYPE SELOPT,
RT_STOCKID TYPE STANDARD TABLE OF SELOPT.
LOOP AT GT_ZB1PUT_STOCKTMP.
RS_STOCKID-SIGN = 'I'.
RS_STOCKID-OPTION = 'EQ'.
RS_STOCKID-LOW = GT_ZB1PUT_STOCKTMP-STOCKID.
APPEND RS_STOCKID TO RT_STOCKID.
CLEAR RS_STOCKID.
ENDLOOP.
You can use this RANGE table to SELECT data from the table.
SELECT * FROM zb1xxt_param
FOR ALL ENTRIES IN gt_zb1put_stocktmp[]
WHERE zzcode = 'DEV036'
AND zzdomain = 'SD'
AND zzdata = 'INBOUND'
AND zzinput1 = 'STOCKID'
AND zzinput2 IN RT_STOCKID. "Use RT_STOCKID for SELECT'ing data
BR,
Suhas -
Use Of "#EC CI_EXECSQL in ABAP with EXEC SQL. Statement giving Syntax Error
Dear Gurus,
I have encountered an issue while trying to remove warning for using Native SQL statement using pseudo comment "#EC CI_EXECSQL
The thing is like this -- i have used follwing native sql command in abap.
EXEC SQL.
CONNECT TO 'SURROUND_DB'
ENDEXEC.
Now when i am checking this code in code inspector it is showing a warning with information below
CA CL_CI_TEST_CRITICAL_STATEMENTS0006
Code Inspector
Critical Statements
Use of Native SQL
Authorization checks cannot be appropriately run using EXEC SQL and should be carried out at program level.
The message can be hidden using the pseudo-comment "#EC CI_EXECSQL
Use of exceptin handling section for that warning showing me to use :
The message can be hidden using pseudo
comment "#EC CI_EXECSQL
Now when I am using "#EC CI_EXECSQL in the abap like below :
EXEC SQL. "#EC CI_EXECSQL
CONNECT TO 'SURROUND_DB'
ENDEXEC.
It is giving syntax error
The text literal ""#EC CI_EXECSQL " is longer than 255
characters.Check whether it ends correctly.
Please provide the guideline to resolve this issue.
Thanks & regards
Saifur Rahaman.Hi Saifur,
You can remove the warning using the following syntax:
EXEC "#EC CI_EXECSQL
SQL.
CONNECT TO 'SURROUND_DB'
ENDEXEC.
At least, it worked fine for me when using OPEN CURSOR, SELECT, FETCH and so on statements.
The way to use the pseudo comment is not very intuitive, but at least for my examples worked fine.
I hope this may help you.
Best regards,
Edgardo G. König
Maybe you are looking for
-
Sales order cost estimate with GIT account
Hi, Business introduced Goods - in - Transit (Balance sheet account), so PGI will always post to GIT and Invoice it will get reversed. For one of the Configuratble material (MTO) scenario we need the Sales order cost estimate to get the Planned cost.
-
How can I Loose the Heat or Fan Control in G4 Tower?
I have a G4 FW 800 Tower that is running hotter with 10.5.x and knowing that heat kills hardware, I'd like to use the existing internal fans that do a great job when they fire up, to cool it down as I have seen them do. I have a temperature monitor a
-
Exchange User IP - Get Object Returns Body of E-Mail As HTML
All, Using Orchestrator to monitor a mailbox and create System Center Service Manager incident from it. I am utilizing the Activity Directory User IP to monitor to the mailbox, pull the subject/body/send from the e-mail, and create an incident. Every
-
My PC seems to have had its day and I'm thinking of buying a laptop and changing to a wireless connection. (Currently use a Voyager 220V modem.) Could anyone outline the procedure? Do I simply change my broadband package and receive a free hub and w
-
I have formed this as a complaint in this discussion previously but the moderators keep deleting it for some reason so perhaps if I phrase it in the form of a question..... Anyway, here is my question. Does anyone have a good or technical explanation