Declare variable as column

  • Hello!

    Is this possible in some way?

    SELECT 'Hello' AS ThisDoesntExist

    FROM sometable

    WHERE ThisDoesntExist = 'Hello'

    It gives me the error that the column doesn't exist, so I wonder if its possible to declare it as a column...

  • Maybe not enough coffee, but I don't get it..

    Can you explain what you're trying to do?

    /Kenneth

  • I think it is to do with selecting a column dynamically ?!?!?!







    **ASCII stupid question, get a stupid ANSI !!!**

  • I have four tables with im joining with a UNION ALL, and dynamically adding a column which unique identifies the four tables.. like this resultset:

    COL1, COL2, COL3, ThisDoesntExist

    VAL1   VAL2   VAL3   one

    VAL1   VAL2   VAL3   two

    VAL1   VAL2   VAL3   three

    Where one, two and three is the "unique table identifier" set to some value... such as "thisisfromtable1" and so on.

    Thats the idea. I could just add a real column in each table with some value but i dont want that in this situation.

  • That'll work. But the next where condition will be executed later so the column will exist for that statement even if it doesn't exists in any of the tables...

  • Ah... (had my coffee now) Something like this?

    use northwind

    select customerId,

           'Customers' as 'origin'

    from   customers

    union all

    select customerId,

           'Orders'

    from   orders

    customerId origin   

    ---------- ---------

    ALFKI      Customers

    ANATR      Customers

    ANTON      Customers

    ..................

    ANATR      Orders

    ANATR      Orders

    ANTON      Orders

     

    /Kenneth

  • Yes exactly. But what happens if you use a WHERE clause there? it says that the column doesnt exist, that is my problem..

     

    select customerId,

           'Customers' as 'origin'

    from   customers

    union all

    select customerId,

           'Orders'

    from   orders

    That works, but not with "WHERE origin = something"...

     

  • Just don't select the data if you don't need it. Why would you want to do that?

  • Wrap the union in a select then execute the where from the wrapper:

    Select * From

    (

    Your UNION

    ) dt

    where origin = 'x'

     


    * Noel

  • Maybe we need an explanation about what the purpose behind this request is? I mean, I don't understand why you would declare a few constants, and then filter on those constants in a WHERE clause? The constants have nothing to do with the data selected, so (as Remi said) don't select those in the first place...?

    /Kenneth

  • Use noeld suggestion or make a view from you UNION statement and select from this view using any kind of WHERE clause you like.

    _____________
    Code for TallyGenerator

Viewing 11 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic. Login to reply