Sql Transposing Column Name in Row

i am using Sql Server 2008
tbl_EmployeeProfile
EmployeeId EmployeeName LeaveApplicable Active
1 Sam true true
2 Rahul false false
3 Sameer true true
tbl_MasterLeave
id LeaveCode Description active
1 PL Paid Leave true
2 CL Casual Leave true
3 SL Sick Leave false
tble_LeaveAllocation
EmployeeId Period 1 2 3 .........31
1 2014 18 4
3 2014 20 4
note: tble_Masterleave.id = tble_LeaveAllocation.1( column Name)
i.e  value of tbl_masterleave id is mape with column name of tble_LeaveAllocation 1,2,.....31
Expected out put
EmployeeId EmployeeeName Period PL CL
1 Sam 2014 18 4
3 Sameer 2014 20 4
Note: show only record who is active = true & leaveApplicable = true  .
why i made this table structure  because non of organization leave type are not fixed, so user can customize leave according their requirment , so i made tbl_ allocation table with 1 to 31 column , so user can allocate leave type max 31.
please advice me is it right method or any other good alternative solution 
Thanks Best Regard Naweez

Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
Why are you so special that you do not have to post DDL? I Googled you and got nothing that would grant you privilege. 
You have the manners of a pig and your code is garbage. Look up tibbling in the “code smells” paper. That is what we call your “tbl-”
 prefix when we laugh at you. 
Why do you write SQL with assembly language flags? SQL programmers do not! Why did you use the term “master_” on a table name? This term is from tape files and network DB; it has nothing to do with RDBMS!! 
Why do you think that “active” is an attribute? NO! It is a value of some particular attribute and needs a temporal range. 
There is no generic “id” in RDBMS! Remember the Law of Identity from your first freshman logic class? Rows are not records, so you got that term wrong. We do not use mappings in RDBMS; we have REFERENCES. 
CREATE TABLE Personnel
(emp_id CHAR(10) NOT NULL PRIMARY KEY,
 emp_name VARCHAR(35) NOT NULL);
CREATE TABLE Leave_Codes
(leave_code CHAR(2) NOT NULL PRIMARY KEY,
 leave_code_description VARCHAR (20) NOT NULL);
INSERT INTO Leave_Codes
VALUES 
('PL', 'Paid Leave'),
('CL', 'Casual Leave'),
('SL', 'Sick Leave);
I might have done this: 
CREATE TABLE Employee_Leaves
(emp_id CHAR(10) NOT NULL
 REFERENCES Personnel(emp_id)
 leave_start_date DATE NOT NULL,
 leave_end_date DATE NOT NULL,
CHECK(leave_start_date < leave_end_date),
 leave_code CHAR(2) NOT NULL
  REFERENCES Leave_Codes (leave_code),
 PRIMARY KEY (??),
 >> why I made this table structure because our organization leave type are not fixed, so user can customize leave according their requirement, so I made allocation table with 1 to 31 column, so user can allocate leave type max 31. <<
No, you did this out of ignorance. You do not understand RDBMS or SQL.  YHou do not know any of the basics. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Transposing column names to row for a multi row table

    Hi
    I have a table some thing like this that needs to be transposed.
    FIELD_POPULATED First_NM**Last_NM**Mi_NM*
    A_NULL 0 0 0
    A_NOT_NULL 120 120 120
    B_NULL 0 0 0
    B_NOT_NULL 0 0 0
    The above table has to be transposed as
    column_name*A_NULL**A_NOT_NULL**B_NULL* B_NOT_NULL
    FIRST_NM 0 120 0 0
    Last_NM 0 120 0 0
    Mi_NM 0 120 0 0
    I am working oracle on 11g. Any help is greatly appreciated

    Hi,
    See this thread:
    Re: Help with PIVOT query (or advice on best way to do this)

  • [[DataDirect][ODBC SQL Server Wire Protocol driver][Microsoft SQL Server]Column name or number of supplied values does not match table definition.]

    Hii ..
    need help on this ..
    This what I am doing ..
    I am using a DATAEXPORT function to export level0 data from my essbase 11.1.2.2 to Microsoft SQL 2008 tables.
    So what I did first I exported the level0 data to a flat file using DATAEXPORT and the created the SQL columns by the same  in that order only in my SQL table.
    When I run it fails with this error:
    ODBC Layer Error: [21S01] ==> [[DataDirect][ODBC SQL Server Wire Protocol driver][Microsoft SQL Server]Column name or number of supplied values does not match table definition.]
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1021014)
    ODBC Layer Error: Native Error code [213]
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Error(1012085)
    Unable to export data to SQL table [dataexp]. Check the Essbase server log and the system console to determine the cause of the problem.
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1021002)
    SQL Connection is Freed
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Warning(1080014)
    Transaction [ 0x1c50001( 0x51ee7d66.0x80342 ) ] aborted due to status [1012085].
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1012579)
    Total Calc Elapsed Time for [test.csc] : [1.44] seconds
    =============================================================
    I did a simple test on my Sample.basic application then ..
    loaded the calc data to it and then used the below script to export to a flat file
    //ESS_LOCALE English_UnitedStates.Latin1@Binary
    SET DATAEXPORTOPTIONS
                    DataExportLevel "Level0";
                    DataExportOverwriteFile ON;
                    DataExportColFormat OFF;
                    DataExportDimHeader OFF;
    FIX(
                "Jan",
                "Sales",
                "Actual"
    /*DATAEXPORT "File" "," "/home/hypadmin/samtest.txt";*/
    DATAEXPORT "DSN" "Abhitest" "sample" "sa" "welcome1";
    ENDFIX
    out put as below:
    "Sales"
    "100-30","California"
    "Jan","Actual",145
    Now In sql I created only 3 columns with name Jan/Sales/Actual and when I run this script again with comments removed .. I get the same error as what I have got in my first test case with other application ..
    but when I create the columns with same name as what its in export
    Sales/100-30/Califirnia/Jan/Actual
    It created the new rows successfully ..
    So with this I think the error which I am getting with my other application might be because of the same column issue  .. but then I have created all the columns by looking at the export file only as I did in sample ..
    Any idea would be helpful ..
    Thanks
    Abhishek
    I

    First make sure you add
    DataExportRelationalFile ON;
    to your set commands it is missing
    I alwats like to also add
    DataExportColHeader dimensionName;
    so I am sure what dimension is getting put into the columns.
    Then count the number of dimensions in your outline (exclude attribute dimensions). You need at least that many columns in your table  -1 + the number of  members you will be returning as columns in the export
    Taking your example Sample basic has 5 dimensions
    Measures
    Years
    Scenario
    Product
    Market
    Since you did not specify a dataexportcolheader it took the dense dimension Scenario as the columns. Your fix statement is limiting that to one member. Doing the math
    5 -1 + 1 = 5 columns in your table which is what you found works.  Suppose you fixed on bothe Actual and budget in scenario then you would need 6 columns 5 -1 +2

  • Use variable in SQL for column name

    Hi All,
    We want to use a user input as a column name in APEX.
    For e.g user will enter "ALLOWABLE_AMOUNT" then the query will be as follows  :
    select Rule,rule_name,rule_desc,"User Input" from rule_dim
    where "User_input" > 100
    So here the User_input will be substitued with Allowable_amount. Is this doable using any bind/substitution variables ? I tried ":P2_USER_VARIABLE" and "&P2_USER_VARIABLE." but did not work.
    Please advice.

    Hi Andy,
    You do that with an Interactive Report and a Dynamic Action.
    I'll assume that you're using APEX 4.2
    Here's how:
    Create Page 2 with an Interactive Report
    Create New Page > Report > Interactive Report > Next > Next
    Enter a SQL Select statement: select Rule,rule_name,rule_desc from rule_dim
    Next > Create > Edit Page
    Create the item P2_USER_VARIABLE
    Add Item > Number Field > Next
    Item Name: P2_USER_VARIABLE
    Next > Next > Next
    Source Used: Always, replacing any existing value in session state
    Source Type: Static Assignment (value equals source attribute)
    Create Item
    Create a Dynamic Action to refresh the Interactive Report when P2_USER_VARIABLE is changed
    Add Dynamic Action
    Name: Refresh IRR
    Next >
    Event: Lose Focus
    Selection Type: Item(s)
    Item(s): P2_USER_VARIABLE
    Next >
    Action: Refresh
    Next >
    Selection Type: Region
    Region: Report 1 (10)
    Create Dynamic Action
    Add the ALLOWABLE_AMOUNT to the Interactive Report
    Report 1
    Region Source: SELECT * FROM (select Rule,rule_name,rule_desc, :P2_USER_VARIABLE AS ALLOWABLE_AMOUNT from rule_dim) WHERE ALLOWABLE_AMOUNT > 100
    Apply Changes > Apply Changes
    Get the Interactive Report to submit P2_USER_VARIABLE
    Report 1
    Page Items to Submit: P2_USER_VARIABLE
    Apply Changes
    Change the Heading for ALLOWABLE_AMOUNT in the Interactive Report
    Interactive Report
    Change the Heading of ALLOWABLE_AMOUNT to &P2_USER_VARIABLE.
    Apply Changes
    Run
    Enter something into the USER VARIABLE field and select something else on the page. Watch the last column update to that value.
    Tim.

  • SQL Alter Column Name

    I am trying to change the name of a column in my Oracle database using SQL PLUS. This is what I'm doing:
    ALTER TABLE projects
    RENAME COLUMN thomas_comp_type TO thomas_comp_shipped_via;
    When I do this it gives me an error stating ORA-14155 Missing PARTITION or SUBPARTITION keyword.
    What does this mean and how do I fix it?

    Hang on: you're trying to rename a column called NAME?
    That's one of Oracle's reserved keywords so should never have been used as a column name in the first place:
    SQL> select * from v$reserved_words where keyword like 'NAME';
    KEYWORD                            LENGTH R R R R D
    NAME                                    4 N N N N NThat said, you are able to do such a rename without an issue in 10g:
    SQL> create table t1 (name varchar2(10));
    Table created.
    SQL> alter table t1 rename column name to fred;
    Table altered.
    SQL> desc t1;
    Name                                      Null?    Type
    FRED                                               VARCHAR2(10)Oracle 9i is obviously a different matter ...and it doesn't help that it's such an old version, because I don't have a machine running that to hand to test things out on. You could try double-quoting the column name:
    SQL> alter table t1 rename column "FRED"  to barney;
    Table altered.But I can't guarantee that will work.

  • MS SQL - Add column with all rows being "0"

    Add column with all rows being "0"

    nevermind
    "lee" <[email protected]> wrote in message
    news:e3b5kt$mch$[email protected]..
    > Add column with all rows being "0"
    >
    >
    >

  • Using SQL alias column names in same SQL

    Hi,
    I am converting some Teradata SQL queries and these queries have the ability to use column defined aliases within the same query, something like :
    SQL> select 'test' as alias1, 'test2' as alias2, alias1 from dual
    Does anyone know how I can get Oracle to do this ????
    Many thanks
    Ben

    Hi,
    Yes I did think of that - its just the queries calculated columns are quite large - sample below show a value calculated currently based on alias names - just trying to find an easier way to apply.
    I was hoping for some magical syntax that has eluded me !
    Ben
    (exp(case when (constant_contrib + fsnumber_contrib + herolevel_contrib + is_colmans_contrib + is_heinz_contrib + is_short_life1_contrib + is_short_life2_contrib + is_short_life3_contrib + logcount_prod_contrib + offer_shelf_cap_contrib + promointensity_contrib + std_shelf_cap_contrib + xforprice_add_1_contrib + ( (power(sh_ms_variables.xfspr,1)) * formula_coefficients.coeff_xfspr1 ) + ( (power(sh_ms_variables.xfspr,2)) * formula_coefficients.coeff_xfspr2 ) + ( (power(sh_ms_variables.xfspr,3)) * formula_coefficients.coeff_xfspr3 ) + ( (power(sh_ms_variables.xfspr,4)) * formula_coefficients.coeff_xfspr4 ) + ( sh_ntnl_variables.xnfor2 * formula_coefficients.coeff_xnfor2 ) + ( sh_ms_variables.xnforfs1 * formula_coefficients.coeff_xnforfs1 ) + ( sh_ms_variables.xnforfs2 * formula_coefficients.coeff_xnforfs2 ) + ( sh_ms_variables.xnforfspl * formula_coefficients.coeff_xnforfspl ) + ( sh_ntnl_variables.xnforpl * formula_coefficients.coeff_xnforpl ) + ( (power(sh_ms_variables.xpr,1)) * formula_coefficients.coeff_xpr1 ) + ( (power(sh_ms_variables.xpr,2)) * formula_coefficients.coeff_xpr2 ) + ( (power(sh_ms_variables.xpr,3)) * formula_coefficients.coeff_xpr3 ) + ( (power(sh_ms_variables.xpr,4)) * formula_coefficients.coeff_xpr4 )) < 500 then (constant_contrib + fsnumber_contrib + herolevel_contrib + is_colmans_contrib + is_heinz_contrib + is_short_life1_contrib + is_short_life2_contrib + is_short_life3_contrib + logcount_prod_contrib + offer_shelf_cap_contrib + promointensity_contrib + std_shelf_cap_contrib + xforprice_add_1_contrib + ( (power(sh_ms_variables.xfspr,1)) * formula_coefficients.coeff_xfspr1 ) + ( (power(sh_ms_variables.xfspr,2)) * formula_coefficients.coeff_xfspr2 ) + ( (power(sh_ms_variables.xfspr,3)) * formula_coefficients.coeff_xfspr3 ) + ( (power(sh_ms_variables.xfspr,4)) * formula_coefficients.coeff_xfspr4 ) + ( sh_ntnl_variables.xnfor2 * formula_coefficients.coeff_xnfor2 ) + ( sh_ms_variables.xnforfs1 * formula_coefficients.coeff_xnforfs1 ) + ( sh_ms_variables.xnforfs2 * formula_coefficients.coeff_xnforfs2 ) + ( sh_ms_variables.xnforfspl * formula_coefficients.coeff_xnforfspl ) + ( sh_ntnl_variables.xnforpl * formula_coefficients.coeff_xnforpl ) + ( (power(sh_ms_variables.xpr,1)) * formula_coefficients.coeff_xpr1 ) + ( (power(sh_ms_variables.xpr,2)) * formula_coefficients.coeff_xpr2 ) + ( (power(sh_ms_variables.xpr,3)) * formula_coefficients.coeff_xpr3 ) + ( (power(sh_ms_variables.xpr,4)) * formula_coefficients.coeff_xpr4 )) else 500 end ) - 1) AS uplift,
    Edited by: user485052 on Dec 10, 2010 3:08 AM

  • T-SQL - Using Column Name in where condition without any references when having multiple tables that are engaged using multiple joins.

    Hi All,
    I am a newbie for T-Sql, I came across a SP where multiple tables are engaged using multiple joins but the where clause contain  a column field without any table reference  and assigned  for an incoming variable,like 
    where 'UserId = @UserId'
    instead -  no table reference like 'a.UserId = @Userid'   ............ Can any please do refer to me any material that clears my mind regarding such issue................... help is appreciated.
    Thank You.

    As suggested above, use table alias with columns for unique referencing and to make the code easier to read.
    BOL example for table aliasing:
    USE AdventureWorks;
    GO
    SELECT S.CustomerID, S.Name AS Store, A.City, SP.Name AS State, CR.Name
    AS CountryRegion
    FROM Sales.Store AS S
    JOIN Sales.CustomerAddress AS CA ON CA.CustomerID = S.CustomerID
    JOIN Person.Address AS A ON A.AddressID = CA.AddressID
    JOIN Person.StateProvince SP ON
    SP.StateProvinceID = A.StateProvinceID
    JOIN Person.CountryRegion CR ON
    CR.CountryRegionCode = SP.CountryRegionCode
    ORDER BY S.CustomerID ;
    GO
    GO
    LINK:
    http://technet.microsoft.com/en-us/library/ms124824(v=sql.100).aspx
    Check the use of TABLE ALIASes and COLUMN ALIASes in the following blog:
    http://www.sqlusa.com/bestpractices2005/organizationtree/
    Without the use of aliases the code would become unreadable.
    Kalman Toth Database & OLAP Architect
    Free T-SQL Scripts
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Column name or number of supplied values does not match table definition

    Buongiorno a tutti,
    sto cercando di inserire dei record in un database SQL, usando l'oggetto DB tools Insert data. Purtroppo però mi viene segnalato il seguente errore:
    "Exception occured in Microsoft OLE DB Provider for SQL Server: Column name or number of supplied values does not match table definition. in NI_Database_API.lvlib:Rec Create - Command.vi->NI_Database_API.lvlib:Cmd Execute.vi->NI_Database_API.lvlibB Tools Insert Data.vi"
    Il recod viene generato da Labivew usando l'oggetto concatanate string e i campi sono separati da tab. se esporto su Excel sembra tutto corretto e non ho errori. Le colonne del mio database corrispondono a quelle del record e sono tutte varchar. Vi allego la porzione di codice che genera il record.
    Suggerimenti?
    Grazie,
    Davide
    Allegati:
    db.png ‏5 KB

    Per qualche strano motivo l'editor ha convertuito la sequenza di caratteri ":" e  "D" in uno smile

  • Transpose rows to columns with numeric column name

    I am trying to transpose row to columns.
    Here is my data having 3 columns (date, last_retry and count(*) )
    Date last_retry count(*)
    1/2/06 2 13
    1/2/06 1 5
    5/5/06 1 12
    5/5/06 2     9
    Desired Output with columns ( date, 1, 2)
    Date 1 2
    1/2/06 5 13
    5/5/06 12 9
    Here is my query which doesn't work
    select trunc(Date),
    max(Decode(last_retry,'1',count(*))) as 1,
    max(Decode(last_retry,'2',count(*))) as 2
    from retry_state
    1st problem: How do I transpose if this is not correct?
    2nd problem: 1 cannot be named as column name, how can I name the columns
    3rd problem: Suppose I am selecting this data and loading into a table. Now can
    the data be loaded during select as well as transposed at the same time or would I need to create a view to load the data first into table and then perform transpose?

    hi,
    this will transpose your data and insert into the table:
    INSERT INTO transposed_table
    (SELECT my_date,
    MAX(DECODE(last_retry,1,cnt,0)) AS "1",
    MAX(DECODE(last_retry,2,cnt,0)) AS "2"
    FROM retry_state
    GROUP BY my_date)
    note: to avoid problem and confusion, i renamed the fields DATE and COUNT(*) to MY_DATE and CNT respectively. You should avoid using reserved words as your fields such as DATE!
    hope this helps.

  • Transposing columns to rows in excel through ODI

    Hi all,
    We are trying to transpose Columns to rows along with Headers considering excel as source and oracle table as target
    For example we are having metadata and data in Excel sheet like below
    Metadata:- A,B,TC1,TD1,L1,U1,TC2,TD2,L2,U2,TC3,TD3,L3,U3
    Data:-        X,Y,1,2,3,4,5,6,7,8,9,10,11,12
                     M,N,a,b,c,d,e,f,g,h,i,j,k,l
    Then we need in the below way in oracle table
    A,B,TC1,TD1,L1,U1
    X,Y,1,2,3,4
    X,Y,5,6,7,8
    X,Y,9,10,11,12
    M,N,a,b,c,d
    M,N,e,f,g,h
    M,N,i,j,k,l
    Is there any process to achieve this?
    If so Please let us know
    Thanks in advance

    Hi SH,
    Thanks for your reply
    We already tried http://s3.amazonaws.com/Ora/KM_IKM_Pivot.zip by following the link https://community.oracle.com/thread/904535?tstart=0
    But unfortunately we got the same error which is mentioned in that link
    org.apache.bsf.BSFException: exception from Jython:
    Traceback (innermost last):
    File "<string>", line 35, in ?
    java.sql.SQLException: Invalid column name
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    I am newbie to odi - if possible can you please guide me how to do transpose in odi by considering excel as source and oracle as target
    Thanks

  • How to use the column names generated from Dynamic SQL

    Hi,
    I have a problem with Dynamic SQL.
    I have written an SQL which will dynamically generate the Select statement with from and where clause in it.
    But that select statement when executed will get me hundreds of rows and i want to insert each row separately into one more table.
    For that i have used a ref cursor to open and insert the table.
    In the select list the column names will also be as follows: COLUMN1, COLUMN2, COLUMN3,....COLUMNn
    Please find below the sample code:
    TYPE ref_csr IS REF CURSOR;
    insert_csr ref_csr;
    v_select VARCHAR2 (4000) := NULL;
    v_table VARCHAR2 (4000) := NULL;
    v_where VARCHAR2 (4000) := NULL;
    v_ins_tab VARCHAR2 (4000) := NULL;
    v_insert VARCHAR2 (4000) := NULL;
    v_ins_query VARCHAR2 (4000) := NULL;
    OPEN insert_csr FOR CASE
    WHEN v_where IS NOT NULL
    THEN 'SELECT '
    || v_select
    || ' FROM '
    || v_table
    || v_where
    || ';'
    ELSE 'SELECT ' || v_select || ' FROM ' || v_table || ';'
    END;
    LOOP
    v_ins_query :=
    'INSERT INTO '
    || v_ins_tab
    || '('
    || v_insert
    || ') VALUES ('
    || How to fetch the column names here
    || ');';
    EXECUTE IMMEDIATE v_ins_query;
    END LOOP;
    Please help me out with the above problem.
    Edited by: kumar0828 on Feb 7, 2013 10:40 PM
    Edited by: kumar0828 on Feb 7, 2013 10:42 PM

    >
    I Built the statement as required but i need the column list because the first column value of each row should be inserted into one more table.
    So i was asking how to fetch the column list in a ref cursor so that value can be inserted in one more table.
    >
    Then add a RETURNING INTO clause to the query to have Oracle return the first column values into a collection.
    See the PL/SQL Language doc
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/returninginto_clause.htm#sthref2307

  • How to suppress column names in SQL-report

    What I want is just the data, without any column names.
    COLUMN LDATE OFF;
    SELECT     SYSDATE LDATE
    FROM DUAL;
    LDATE
    07.11.11
    This example doesn't work. There is still LDATE above column. Any idea?

    user5116754 wrote:
    Great, it's so simple. Im sure there is a way to omit this result statement: "531 rows selected" at the end of report!There is, and it's also in the documentation...
    SQL> set feedback off
    SQL> select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17-NOV-1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-1987 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 03-DEC-1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-1982 00:00:00       1300                    10
    SQL>

  • How to validate column name in dynamic made sql?

    Oracle db, jdbc, web app with struts2/spring.
    Example table could be this:
    CREATE TABLE album
    album_id number(10)  not null,
      artist  varchar2(50) not null,
    title  varchar2(50) not null,
      released  DATE,  
      CONSTRAINT album_pk PRIMARY KEY (album_id)
    );In may app the user MAY search, MAY sort, and the result from an select might return 10.000 rows.
    The basic sql usually look like this.
    String sql = "select album_id, artist, title, released from album";Then in the html page the user can add search criteria for each column. Like type "iron maiden" in artist field, put "1982" in released field. And you all know what the exceptionally result should be from that :)
    Now I need to modify the sql a bit:
    if( artist search field contains stuff )
       sql = sql + " where nvl( artist,' ') like ?"
    }we try use prepared statements right? So we use ? as placeholders, and then add "iron maiden" into this statement later on.
    Nice, no big fuzz right, and pretty safe from sql injections i guess.
    But now I have to have an if/else for every single field in the table. Boring. In my app I got like 25 tables like this, with 20 columns minimum. Copy/Paste have never been so boring.
    I also might have to add "order by" with user selected columns and their order. I have to count the query to get total result in case i got to split it up in pages. So there is alot of if/else and sql = sql + "more stuff", and sticking to ? and pure prepared statements is impossible.
    But doing this is not good either:
    for( each element in a map)
      sql = sql + " and nvl( " + key + ",' ') like ?"
    }Where key is "artist".
    In struts and other tag libs its easy to make kode like:
    <s:textfield name="model.addSearch( 'artist' )" value="%{model.getSearch( 'artist' )}" size="30" />
    Silly example maybe, but just to make a point.
    Inputed values in an html form, can very easily be a part of a dynamic created sql - which becomes a security problem later on.
    Artist is an column name. Key should be validated if it contained an valid column name.
    I could make a list of strings, containing valid column names to check against.
    My question is if there is possible to get this type of information from the database, so I don't have to hand-make these lists?
    But I also want to keep the number of heavy and slowing queries down.
    My app have like 25 tables now, and I could easily get away with hand-make everything, copy/paste around etc. But I have more projects and this question will be here next time too. And after there again...

    Etharo wrote:
    Metadata. Then I have to query the database, take the result and use it for validating of input. If my sql only query 1 table, then this is ok. In this case I could do with that. But if the sql query mutliple tables, with sub-selects, unions etc. Then I might have to query all tables first, and even then I might not have what I want.
    The best way is of course to run the query, then get the metadata from that query - cause then im 100% sure what columns will be returned, and then I can validate with that.... 1 query is often not that slow. But I might query once to find total number of rows the query return in order to decide if we need to page the result. then query to get the metadata for validating input, then query to get the result... Maybe this is ok -but my head don't like it as an general ok thing to do, but I can't really say why...If you have a gui screen then it needs to correspond to some specific query. It can't be all possible combinations.
    So once you know the query you can obtain the meta data using a query that returns no results. Like the following.
    select * from mytable wheren 1 = 0
    >
    Jschell:
    I agree to what you say. I don't understood everything you said tho.
    Im not sure if you talk about having 1 search field (like google), and you input stuff there that might be in any columns.
    I have several search fields in one-to-one relasionship with view column/sql query column.
    Then you already know what the field represents. So validate it in the gui and not via the database.
    The first is way more advanced since you have to cover any input, any column, any case etc. Pluss add ranking. Lots of work for someone who have done little searchengines.
    Latter is simpler, but might also be limiting.Huh?
    As an example if you have a call center then the operators are not going to be doing unrestricted searches to find customers. They are going to look using a very limited set of data like the customer name and telephone number.
    >
    My job is very much like an consulent. They got an app, I shall add a new feature. The app is old and ugly coded. My boss ask how long it takes to make this, I say 2months, he decide 1 month. My dev time for features is rarely above 1 month, and I don't make much new apps.
    So I don't have the time to make advanced codegenerator, or spend time to evaluate various frameworks. Bringing an framework into the existing code is actually difficult. But I do want to improve the code, and add good code into the existing app that can be extended without evil pain.
    That doesn't jive with your OP. You made the following statement "My app have like 25 tables now, and I could easily get away with hand-make everything,...".
    That suggests that you are doing much more than simply updating an existing application.
    If you only need to add one new field then you should do only that. You shouldn't be attempting to add a system spanning validation system.
    On the other hand if you are in fact adding a validation system, then code generation makes it likely that it would take less time or no more than the same. And it is less likely to introduce bugs.
    Learn how to make an code generator? Well I guess thats what I asked help for - point me in the right direction if you could pls. Putting strings together to become code in an logic way is usually manageable, at least for simple querys. Evaluating that the generated code is good/safe - got no good clues...
    Learn about frameworks? Got no time. Hope I will get the time, but I won't. The customer must want to spend the money so I can get the time, that won't happen cause an framework does not add features, its only cost saving in terms of dev time, and maintenance time. The customer have no such focus/interest. They got a bit money to spend now and then regularily. i.e. government.
    I just want to try code as good as possible so I save myself from errors, painfull rewrites, and dev-time that gets out of proportions because of stupid code. So the question is actually about me trying to improve myself, its just that i don't know how right now.There are two goals.
    1. Implement a specific feature in an existing application.
    2. Learn a new way to solve problems.
    Nothing says that the second will help with the first. They should be addressed separately and your post doesn't make it clear what the first is so it is hard to say how it should be down.
    As for the second I already made a suggestion which provides two new ways to solve problems.

  • Problem in displaying row vale as column name

    Hello Experts,
    Please help me,its very urgent....
    i want to dispaly a column value as a column name.
    i have two column into selete statement and i want to dispaly one column value as a column name and other column value as a single row.
    My query is :
    SELECT MAX(DECODE (NAME,'virtualDeviceId',VALUE))vdid ,
    MAX(DECODE (NAME,'virtualDeviceType',VALUE)) vdevtype,
    MAX(DECODE (NAME,'domainName',VALUE)) vdevtype1,
    MAX(DECODE (NAME,'sCTPPortSip',VALUE)) vdevtype2,
    MAX(DECODE (NAME,'signallingIpAddress',VALUE)) vdevtype,
    MAX(DECODE (NAME,'signallingNetworkMask',VALUE)) vdevtype,
    MAX(DECODE (NAME,'uDPPort',VALUE)) vdevtype,
    MAX(DECODE (NAME,'uDPPortEnum',VALUE)) vdevtype,
    MAX(DECODE (NAME,'sCTPPort',VALUE)) vdevtype,
    MAX(DECODE (NAME,'sCTPPortM3UA',VALUE)) vdevtype FROM(          
    SELECT extractvalue(VALUE(l),'/S109:trafficParameters/S109:name'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"') NAME,
         extractvalue(VALUE(l),'/S109:trafficParameters/S109:value'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"') VALUE
         FROM INTERFACE_MESSAGE_DESTINATION imd ,TABLE(xmlsequence(EXTRACT(XMLTYPE(imd.remote_request),'/activateConnection_Payload/jobBody/subnetworkConnection/S109:aEndTerminationPoint/S109:managedElement/S109:physicalTerminationPoint/S109:connectionTerminationPoint/S109:trafficDescriptor/*'
    , 'xmlns="http://itprogrammes.intra.bt.com/pdb/capabilities/ManageDaaliResource/2005/11/16" xmlns:header="http://wsi.nat.bt.com/2005/06/StandardHeader/" xmlns:S97="http://ccm.intra.bt.com/2005/11/16/LIB/Info/CCM/AnalysisModel/Services" xmlns:S109="http://ccm.intra.bt.com/2005/11/16/LIB/Info/MTOSI"'))) l
    WHERE message_id ='NIAS/0000041608') GROUP BY VALUE ;
    output is :
    Col1 Col2 col3 col4 col5 col
    1.'1001105'          '1001105'                                   
    2. 'MGC'                                        
    3.'value' 'value' 'value'
    output display : MGC in Col2 and in row 2, 'values' are in col4 and col5 and in row 3.
    I want all values in a single row.
    Please help me
    Surender Rana

    It is ugly to force multiple rows into a single row. But it can be done and can be done dynamically as the following approach shows.
    SQL> create or replace type TStrings as table of varchar2(4000);
    2 /
    Type created.
    SQL>
    SQL> create or replace function ForceColumns( cur SYS_REFCURSOR ) return TStrings is
    2 setCols TStrings;
    3 setResults TSTrings;
    4 begin
    5 setResults := new TStrings();
    6 loop
    7 fetch cur into setCols;
    8 exit when cur%NOTFOUND;
    9
    10 if setCols.Count > 0 then
    11 setResults.Extend( setCols.Count );
    12 for i in 1..setCols.Count
    13 loop
    14 setResults( setResults.Count-i+1 ) := setCols(i);
    15 end loop;
    16 end if;
    17 end loop;
    18
    19 return(setResults);
    20 end;
    21 /
    Function created.
    SQL>
    SQL> select
    2 ForceColumns(
    3 CURSOR(
    4 select TStrings(object_id,object_name,object_type) from user_objects where rownum <= 5
    5 )
    6 ) as RESULT_SET
    7 from dual
    8 /
    RESULT_SET
    TSTRINGS('TABLE', 'A', '70998',
    'PROCEDURE', 'ABC', '54360',
    'TABLE', 'ANIMALS', '84829',
    'TABLE', 'B', '69604',
    'PROCEDURE', 'BUILDNAMEMAP', '70155')
    SQL>Note that as the row can contain any number of columns, it needs to be dynamic. This approach uses a collection type called TStrings to achieve this.

Maybe you are looking for

  • Loading Data Error while using SQL Loader

    Hi All, I am facing another issue while loading the data from text file to oracle db. I have a table in which data is loaded from multiple files. What i want the when i load the data i want to load the filename as well in the table in front of the re

  • X Application won't display

    Hi everyone, I am having a bit of a problem getting my X application to display out. We are building new Sun servers to replace the existing servers. The new servers are running Solaris 9 with SGD 4.10.903 (with the builin webserver). SGD and the App

  • How to Convert 4:3 footage to 16:9 the best way in FCP??

    Hello, I see a lot of different answers for this but i havent found anything very recent so that is why I ask. I am going to be shooting in 4:3 standard def with my Canon T3i because the only way to shoot in Standard Definition with it is using 4:3.

  • Batch printing - page format issue

    I am creating a smartform in a batch job and sending it to various printers throughout our company.  The form is going to the printer but it attempts to print in the A4 (DINA4) page format.  I have the smartform set to print (under the Form Attribute

  • Easy way to set interpolation on keyframes?

    Say you have text flying in using scale and you want it to start out fast and slow down. When you go in and select Bezier for interpolation, you have to set the curve for the x,y,and z parameters. It is hard to select the right parameter and you have