• CELKO (11/2/2012)


    I want to give variable as column name.

    NO! Please read just one book on RDBMS before you try writing SQL. A column is an attribute of an entity, shown with a scalar value drawn from a domain that is modeled with a single data type.

    Renaming columns is magical thinking. It would be like changing lead into gold. Creating new attributes on the fly is also magical thinking. You wave your wand and the elephant grows wings!

    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML. The report period table gives a name to a range of dates that is common to the entire enterprise.

    CREATE TABLE Report_Periods

    (report_name VARCHAR(30) NOT NULL PRIMARY KEY,

    report_start_date DATE NOT NULL,

    report_end_date DATE NOT NULL,

    CONSTRAINT date_ordering

    CHECK (report_start_date <= report_end_date),

    etc);

    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantage is that it will sort with the ISO-8601 data format required by Standard SQL.

    He's not building a table, Joe. He's trying to build a dynamic cross-tab report.

    Based on teaching SQL for a few decades is that you will need 2-3 years of hard work before you are able to write usable SQL code.

    Not if you have a good teacher.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)