Join on ambiguous column name

I have three tables I am working with. employee_passenger, nonemployee_passenger, employee (linked from another database). I want to outer join the passenger tables on the employee table for a view I am creating. Can I alias the two passenger tables and generically outer join both in one statement?
Example:
SELECT p.pk_passenger_id "Passenger_ID", n.pk_passenger_id "Passenger_ID", e.emp_id
FROM employee_passenger p, nonemployee_passenger n, employee@somewhere e
WHERE Passenger_ID = e.emp_id (+)
Desired result:
Passenger_ID Passenger_ID emp_id
101 9230
102
103 9249
Or would it be better to do something like:
SELECT p.pk_passenger_id, n.pk_passenger_id, e.emp_id
FROM employee_passenger p, nonemployee_passenger n, employee@somewhere e
WHERE p.pk_passenger_id IS NULL OR p.pk_passenger_id = e.emp_id

Consider the following approach:
First union both passenger tables, then join with the emp table (not tested).
SELECT p.pk_passenger_id Passenger_ID, e.emp_id, p.sourcetable
FROM (SELECT 'E' sourcetable, pk_passenger_id
           FROM employee_passenger
           UNION ALL
           SELECT 'NE' sourcetable, pk_passenger_id
           FROM nonemployee_passenger
           ) p,
           employee@somewhere e
WHERE p.pk_Passenger_ID = e.emp_id (+)

Similar Messages

  • Ambiguous column name 'ITEMCODE'.

    hi,
      while executing the query by using stored procedures
    i got this error."Ambiguous column name 'ITEMCODE' ".
    -priya

    Hi priyadharshini
    The error usually means your are joining multiple tables,
    and doesn't clearly state from which table you're trying to retrieve the column.
    Please have a look at this page.
    http://databases.aspfaq.com/database/what-does-ambiguous-column-name-mean.html 
    Regards,
    Syn Qin
    SAP Business One Forums Team

  • INNER JOIN, MX 7, column name error

    I am running or attempting to run the att'd query in CF MX
    7.0 and getting an error because I then run:
    <CFOUTPUT QUERY="getNutes" group="NUTR_NO">
    <CFSET VALUE = 0>
    <CFOUTPUT>
    <CFIF Day EQ "T">
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100) / getDays.RecordCount>
    <CFELSE>
    <CFSET VALUE = VALUE + (getNutes.Total_WT *
    getNutes.NUTR_VAL/100)>
    </CFIF>
    </CFOUTPUT>
    To sum the nutrient contents...
    This worked fine under CF 5... but I am getting a 'NUTR_NO
    does not specify a column name in the query'.
    Any thoughts???
    Query follows:

    > Yep... it's worse... it appears that MX does not support
    the sql inner join or
    > outer join... sigh...
    Don't be ridiculous. You're showing a fundamental lack of
    understanding of
    how CF handles database interaction. When you use
    <cfquery> to "create" a
    recordset, all CF does is resolve any embedded CF (tags,
    functions,
    variables, etc), and passes the resulting string to the DB.
    The DB then
    processes it and returns a recordset. So CF doesn't "support"
    any sort of
    SQL syntax. Now does it claim to; nor does it try to; nor is
    it
    appropriate for it to.
    If you're having problems with your returned recordset, the
    first thing you
    should do is <cfdump> it (or part of it) and check that
    you're getting back
    what you're *assuming* you're getting back.
    The second thing you should do is lose the SELECT *. Specify
    the columns
    you want back. This is nothing to do with CF, it's just
    standard SELECT
    query advice. When you're joining tables, you hardly ever
    want ALL the
    columns back, and if it's one of those rare occasions you DO
    want all of
    them, you should still specify a SELECT clause so you can
    distinguish
    between same-named columns (which seems to be your problem
    here).
    Adam

  • Get column names into a VB program, for an SQL query that joins tables

    use [mydatabase]
    select * from InvNum inum
    left join _btblInvoiceLines ilin
    on inum.autoindex = ilin.iinvoiceid
    left join stkitem s
    on ilin.istockcodeid = s.stocklink where InvNumber = 'IVQ0834' or InvNumber = 'IVQ0835'
    I need to get out the column names in a VB program in the same order they would appear in the SQL query above...
    I want to use something like:
    select column_name from information_schema.columns where TABLE_NAME = ....
    except there are several tables involved above so I dont know the format!

    If you execute the query in your program using the SqlDataReader.ExecuteReader method, the column names will be available via the GetName method of the returned reader.  But note that your query may return multiple columns with the same name.
    Dim reader As SqlDataReader = command.ExecuteReader()
    For x = 0 To reader.FieldCount - 1
    Console.WriteLine(reader.GetName(x))
    Next x
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • How to join two columns between two tables with different column names

    Hi
    How i can join 2 columns with different names between the 2 tables.
    Can any one please give solution for this.
    Thanks
    Manu

    Hi,
    basic understanding of joins:
    If you want to join 2 tables there should be matching column w.r.t. data and it's data type. You need not to have same column names in both the tables...
    so, find those columns which has got same values..

  • AIR 1.5.2 vs AIR 2.0 outer left join - column name issues

    Hi All,
    I was wondering if anyone has seen this or know a workaround to this issue.
    After a machine got updated to AIR 2.0 our apps started to fail. Upon further inspection I discovered that the column names in the return results from an SQLite query using "outer left join" were different between AIR 1.5.2 and AIR 2.0.
    Here's my proof of concept: (I attempted to make this as sort as possible but reproduce the issue)
    private function runTest():void{
                        var conn:SQLConnection = new SQLConnection();
                        var stmt:SQLStatement = new SQLStatement();
                        var res:Array = [];
                        stmt.text = "SELECT tableOne.int, tableAlias.varchar " +
                                  "from tableOne " +
                                  "outer left join (SELECT * FROM tableTwo) as tableAlias " +
                                  "on (tableOne.int == tableAlias.int)";
                        conn.open(File.applicationDirectory.resolvePath("tempdb.db"));
                        stmt.sqlConnection = conn;
                        stmt.execute();
                        conn.close();
                        res = stmt.getResult().data as Array
                        trace(ObjectUtil.toString(res));
    AIR 1.5.2 trace results:
    (Array)#0
      [0] (Object)#1
        tableAlias_varchar = "apple"
        tableOne_int = 0
      [1] (Object)#2
        tableAlias_varchar = "boat"
        tableOne_int = 1
      [2] (Object)#3
        tableAlias_varchar = "cat"
        tableOne_int = 2
    AIR 2.0 trace results:
    (Array)#0
      [0] (Object)#1
        int = 0
        varchar = "apple"
      [1] (Object)#2
        int = 1
        varchar = "boat"
      [2] (Object)#3
        int = 2
        varchar = "cat"

    I'm having an issue which I think is similar but the workaround does not work.
    Using a table like the one below:
    uid
    name
    parentuid
    1
    math
    2
    science
    3
    language arts
    4
    addition
    1
    5
    subtraction
    1
    6
    division
    1
    7
    multiplication
    1
    8
    geology
    2
    9
    physics
    2
    10
    biology
    2
    11
    phonics
    3
    12
    literature
    3
    13
    grammar
    3
    I execute the following query:
    SELECT child.uid, child.name, child.parentuid, parent.uid, parent.name, parent.parentuid
    FROM category AS parent, category AS child
    WHERE child.parentuid=parent.uid
    GROUP BY child.uid
    In AIR 1.5 I get:
    (Array)#0
      [0] (Object)#1
        child_name = "addition"
        child_parentuid = 1
        child_uid = 4
        parent_name = "math"
        parent_parentuid = (null)
        parent_uid = 1
      [1] (Object)#2
        child_name = "subtraction"
        child_parentuid = 1
        child_uid = 5
        parent_name = "math"
        parent_parentuid = (null)
        parent_uid = 1
      [2] (Object)#3
        child_name = "division"
        child_parentuid = 1
        child_uid = 6
        parent_name = "math"
        parent_parentuid = (null)
        parent_uid = 1
    But in 2.0 I get:
    (Array)#0
      [0] (Object)#1
        name = "math"
        parentuid = (null)
        uid = 1
      [1] (Object)#2
        name = "math"
        parentuid = (null)
        uid = 1
      [2] (Object)#3
        name = "math"
        parentuid = (null)
        uid = 1
    I can't think of any way to make this work in both versions.

  • Many to many join table with different column names

    Hi have a joint table with different column names as foreign keys in the joining
    tables...
    e.g. i have a many to many reltnshp btwn Table A and Table B ..and join table
    C
    both have a column called pk.
    and the join table C has columns call fk1 and fk2
    does cmd require the same column name in the join table as in the joining table?
    are there any workarounds?
    thanks

    HI,
    No, the foreign key column names in the join table do not have to match the primary
    key names in the joined tables.
    -thorick

  • Dynamic ordering ambiguous column issue

    I'm working on a stored procedure that will accept a column name from a web application.  The stored procedure will use the @SortColumn to sort the results of the query.  I'm receiving ambiguous column errors when the column values are passed in
    to the query.  The original query is written using dynamic sql but I created a simple query to reproduce the issue.   Can someone review the sample below and let me know if there is a way to resolve the error. 
    In the example below, the Over(Order by Emp_ID) section is causing the error. The order by is expecting e.Emp_ID as the order by value.  Is there anyway for me to rewrite the logic to allow the correct column alias to be using in the order by statement? 
    Ultimately, I would like to pass in a paramter for the order by column.  Ex.   Over(Order by ' + @SortColunm + '
    SELECT RowNum
    ,Emp_ID
    ,First_Name
    ,Last_Name
    From (Select Distinct ROW_NUMBER() OVER(Order by Emp_ID) as RowNum,
    e.Emp_ID as Emp_ID
    ,e.First_Name as First_Name
    ,e.Last_Name as Last_Name
    FROM Employee e
    LEFT OUTER JOIN Team t ON e.team_id = t.team_Id AND e.Emp_id = t.Emp_Id
    LEFT OUTER JOIN AccrualType at ON e.Accrual_Type = at.Type
    LEFT OUTER JOIN ClosingProcess cp ON e.Emp_id = cp.Emp_ID
    where Last_Name like 's%'
    ) As Employees
    order by Emp_ID

    I've updated my query to use a cte and also included the Row_Number logic.  I'm now receiving "Invalid column name 'RowNum".  Can anyone explain what I'm doing wrong in the code below?   I'm trying to create a stored procedure
    that accepts a parameter to handle paging and sorting.  The dynamic sql is needed for the SortExpression.
    declare @SortExpression varchar(50) = 'Last_Name';
    declare @DynSql varchar(max)='';
    declare @Emp_ID NVARCHAR(50) = NULL
    declare @First_Name VARCHAR(50) = NULL
    declare @Last_Name VARCHAR(50) = 's'
    declare @StartIndex INT
    declare @MaximumRows INT
    set @DynSql=
    With Employees as
    ( Select Distinct
    e.Emp_ID as Emp_ID
    ,First_Name
    ,Last_Name
    FROM Employee e
    LEFT OUTER JOIN Team t ON e.team_id = t.team_Id AND e.Emp_id = t.Emp_Id
    LEFT OUTER JOIN AccrualType at ON e.Accrual_Type = at.Type
    LEFT OUTER JOIN ClosingProcess cp ON e.Emp_id = cp.Emp_ID
    SELECT ROW_NUMBER() Over (Order By ' + @SortExpression + ') As RowNum,
    Emp_ID
    ,First_Name
    ,Last_Name
    FROM Employees
    WHERE RowNum BETWEEN ' + CAST(@StartIndex as varchar(10)) + ' AND ' + '(' + CAST(@StartIndex as varchar(10))+ CAST(@MaximumRows as varchar(10))+ ') - 1 '
    If @Emp_ID is not null
    Set @DynSql = @DynSql + ' And (Emp_ID = @Emp_ID)'
    If @First_Name is not null
    Set @DynSql = @DynSql + ' And (First_Name = @First_Name)'
    If @Last_Name is not null
    Set @DynSql = @DynSql + ' And (Last_Name = @Last_Name)'
    exec (@DynSql)

  • Referencing table-aliased column names in JDBC

    We are attempting to port an application from MySQL to Oracle 8i, using JDBC as the database connection technology. The app has SQL statements using joins, e.g.
    SELECT A.*, B.* FROM table1 A, table2 B WHERE A.field1=B.field2 etc
    Often the tables have columns sharing the same name, so the table alias is required to avoid ambiguity (e.g. both tables have column ID, so they must be referenced as A.ID or B.ID).
    When using MySQL, the Java code
    String strField = rset.getString( "SURNAME" );
    or
    String strField = rset.getString( "A.SURNAME" );
    both succeed if the column name is unique, and if it is not unique, only the second form works. However, with Oracle, the second form never works, even though the column name is a valid column in the table aliased as A. Providing the whole table name does not work either:
    String strField = rset.getString( "table1.SURNAME" );
    If the Oracle JDBC driver does not support the {table-alias}.{column-name} syntax, then presumably the only way to reference ambiguous columns in joins is to supply the column number instead. (e.g. getString( 14 )). Our application generates dynamic SQL, and having to do this would be a MAJOR problem.
    We are currently using Oracle 8i - might this have been fixed in the move to 9i?
    Many thanks for any help,
    Steve Francis,
    London, UK.

    Can't do it by alias, as you would just repeat the
    calculation/function/whatever and add whatever additional "stuff"
    to create your new column.
    ISNULL(row1, 99999) AS ideal,
    ISNULL(row1, 99999)+10 AS newideal
    etc.
    Phil

  • How to Select data using same column name from 3 remote database

    Hi,
    Can anyone help me on how to get data with same column names from 3 remote database and a single alias.
    Ex.
    SELECT *
    a.name, b.status, SUM(b.qty) qantity, MAX(b.date) date_as_of
    FROM
    *((table1@remotedatabase1, table1@remotedatabase2, table1@remotedatabase3)a,*
    *(table1@remotedatabase1, table1@remotedatabase2, table1@remotedatabase3)b)*
    WHERE b.dept = 'finance'
    AND a.position = 'admin'
    AND a.latest = 'Y' AND (b.status <> 'TRM') AND b.qty > 0;
    GROUP BY a.name, b.status ;
    NOTE: the bold statements is just an example of what I want to do but I always gets an error beacause of ambiguous columns.
    Thanks in advnce. :)
    Edited by: user12994685 on Jan 4, 2011 9:42 PM

    user12994685 wrote:
    Can anyone help me on how to get data with same column names from 3 remote database and a single alias.Invalid. This does not make sense and breaks all scope resolution rules. And whether this is in a single database, or uses tables across databases, is irrelevant.
    Each object must be uniquely identified. So you cannot do this:
    select * from (table1@remotedatabase1, table1@remotedatabase2, table1@remotedatabase3) a3 objects cannot share the same alias. Example:
    SQL> select * from (dual, dual) d;
    select * from (dual, dual) d
    ERROR at line 1:
    ORA-00907: missing right parenthesisYou need to combine the objects - using a join or union or similar. So it will need to be done as follows:
    SQL> select * from (select * from dual d1, dual d2) d;
    select * from (select * from dual d1, dual d2) d
    ERROR at line 1:
    ORA-00918: column ambiguously definedHowever, we need to have unique column names in a SQL projection - so the join of the tables need to project a unique set of columns. Thus:
    SQL> select * from (select d1.dummy as dummy1, d2.dummy as dummy2 from dual d1, dual d2) d;
    DUM DUM
    X   X
    SQL> I suggest that you look closely at what scope is and how it applies in the SQL language - and ignore whether the objects referenced are local or remote as it has no impact to fundamentals of scope resolution.

  • Searching for missing column names in a single database.

    I have a database with about 100 tables, database gets generated using entity framework. The application has been enhanced  so users deployed with older version of the application need to upgrade to newer version. The database generated is both versions
    is same name.
    Now, the older version is missing some tables and column names that are in new database.
    Is there a script that can search for missing fields in a single database as described in this situation?
    Below is my script. Basically, nameofdatabase would the database generated and that already existing. If you install the application and database already exits no new database will be created.
    SELECT * FROM (Select TABLE_CATALOG, Table_name,COLUMN_NAME FROM nameofdatabase.INFORMATION_SCHEMA.COLUMNS) a FULL OUTER JOIN (SELECT TABLE_CATALOG, Table_name,COLUMN_NAME FROM nameofdatabase.INFORMATION_SCHEMA.COLUMNS) b ON b.COLUMN_NAME=a.COLUMN_NAME and
    a.TABLE_NAME=b.TABLE_NAME WHERE b.COLUMN_NAME is null or a.COLUMN_NAME is null ;

    There is a great tool called SQLCompare provide by www.red-gate.com
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Automatic Report Bursting based on column names given by user as parameter.

    Hi,
    Could some help me achieve the following functionality. The requirement are:
    1. create a report that has parameters that are column names (display values e.g: department, location, employee job code)
    2. the end user will select one or more columns from the multi-select parameter
    3. we want that there should be a button on clicking that the user should get automatic file bursting. He should not be required to go to schedules tab and create a new job for that.
    4. the report should burst to a file location depending on the columns selected by the user, e.g. if user selected department and location then we should have files saved in the set file location as sales-india.pdf, sales-us.pdf, hr-india.pdf, hr-us.pdf and so on.
    I am new to BI Publisher.
    Could you help me in creating such a parameter, what should be report sql for capturing the data from parameter and then doing report bursting automatically based on two or more parameter values given by the user.
    There is no need to show the report to the user in BI Publisher as there are thousands of rows in a table. Three tables join to give the employee data.
    -Priyanka

    Thanks for a quick response but I am still not clear on
    1. how to do this using custom java code
    and
    2. actually user would login to interactive dashboard and there he will give these parameters using which we need to automatically burst a BI publisher report. Can this be done some how?
    -Priyanka

  • How to select columns in a table by their column id and not the column name

    Hello,
    How do you select columns from a table based on their column_id.
    I have create a view
    but other than Select * , i cant now select one just one column from it
    the view as follow:
    create view count_student as
    select a.acode "acode",aname "Activity Name",count(ae.acode) "Number of student joined"
    from aenrol ae, activity a
    where a.acode= ae.acode
    group by a.acode,aname;

    The issue is that you have decided to use quoted column names. A pretty horrible idea (mostly for the reasons that you are now finding).
    Re-create the view and get rid of the silly double quotes.

  • How to get only column names from different tables as single table columns

    Hi All,
       I have one requirement in which we want only column names from different tables.
    for example :
     I have three tables T1 ,T2, T3 having
      col1 clo2 clo3 -->  T1 , 
      col3 col5 ,clo6 --> T2 ,
      Clo6 col8 col9 --> T3
    columns i want to get only all  Column names from all table as single Resultset not any data from that how can i get that empty resultset 
    because this empty result i want to bind in datagridview(front end) as Empty resultset 
    Please tell me anyways to do this
    Niraj Sevalkar

    If I understand you want an empty result set, just with metadata. SET FMTONLY do the trick:
    SET FMTONLY ON
    SELECT Col1, Col2, Col3, ....., Coln
    FROM
    T1 CROSS JOIN T2 CROSS JOIN T3
    SET FMTONLY OFF
    Another alternative is to include an imposible contition
    SELECT Col1, Col2, Col3, ....., Coln
    FROM
    T1 CROSS JOIN T2 CROSS JOIN T3
    WHERE 1 = 0
    If you are using a SqlDataAdapter in your client application. You can use the FillSchema method. the select command may be any select statement that returns the columns you want. Under the covers FillSchema will call SET FMTONLY ON.
    If you are using SqlCommand.ExecuteReader you can pass SchemaOnly to CommandBehavior argument. SET FMTONLY ON is called under the covers. Again the select command may be any select statement that returns the columns you want.
    "No darás tropezón ni desatino que no te haga adelantar camino" Bernardo Balbuena

  • I need the "Real" Table / Table Column names from a sql view

    Firstly, we have a system with ~1000 tables and ~250 views.  We have field level security on the table columns (in our code)
    Now we have a lot of views which select data from the tables, but I need to get the "Table Column Name" that is linked in the view. 
    I know there are view columns that is not linked to a specific table column, (or concatenation of columns) so those columns can just return NULL.
    From the sample you will see there is a view selecting data from another view.  I know it is not the best sql performance (execution path) but that is another topic on its own.
    I went through a lot of the sys.* stored procs or sys.* views to try and figure out if there is a view that we can use to get the expected results.
    here is the sql code:
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'AliasView2')
    drop view dbo.AliasView2
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'AliasView1')
    drop view dbo.AliasView1
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'Table4')
    BEGIN
    alter table dbo.Table4
    DROP CONSTRAINT [FK_T4_T3]
    alter table dbo.Table4
    DROP CONSTRAINT [PK_T4_Constraint]
    drop table dbo.Table4
    END
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'Table3')
    BEGIN
    alter table dbo.Table3
    DROP CONSTRAINT [FK_T3_T2]
    alter table dbo.Table3
    DROP CONSTRAINT [PK_T3_Constraint]
    drop table dbo.Table3
    END
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'Table2')
    BEGIN
    alter table dbo.Table2
    DROP CONSTRAINT [FK_T2_T1]
    alter table dbo.Table2
    DROP CONSTRAINT [PK_T2_Constraint]
    drop table dbo.Table2
    END
    if
    Exists (select
    * from
    sys.all_objects
    where name =
    'Table1')
    BEGIN
    alter table dbo.Table1
    DROP CONSTRAINT [PK_T1_Constraint]
    drop table dbo.Table1
    END
    create
    Table dbo.Table1
    T1_PK        int
    NOT NULL
    Identity(1, 1)
    CONSTRAINT [PK_T1_Constraint]
    PRIMARY KEY (T1_PK),
    T1_Field1    varchar
    NULL,
    T1_Field2    varchar
    NULL,
    create
    Table dbo.Table2
    T2_PK        int
    NOT NULL
    Identity(1, 1)
    CONSTRAINT [PK_T2_Constraint]
    PRIMARY KEY (T2_PK),
    T2_Field1    varchar
    NULL,
    T2_Field2    varchar
    NULL,
    T2_FK        int
    NOT NULL
    CONSTRAINT [FK_T2_T1]
    FOREIGN KEY (T2_FK)
    REFERENCES dbo.Table1
    (T1_PK)
    create
    Table dbo.Table3
    T3_PK        int
    NOT NULL
    Identity(1, 1)
    CONSTRAINT [PK_T3_Constraint]
    PRIMARY KEY (T3_PK),
    T3_Field1    varchar
    NULL,
    T3_Field2    varchar
    NULL,
    T3_FK        int
    NOT NULL
    CONSTRAINT [FK_T3_T2]
    FOREIGN KEY (T3_FK)
    REFERENCES dbo.Table2
    (T2_PK)
    create
    Table dbo.Table4
    T4_PK        int
    NOT NULL
    Identity(1, 1)
    CONSTRAINT [PK_T4_Constraint]
    PRIMARY KEY (T4_PK),
    T4_Field1    varchar
    NULL,
    T4_Field2    varchar
    NULL,
    T4_FK        int
    NOT NULL
    CONSTRAINT [FK_T4_T3]
    FOREIGN KEY (T4_FK)
    REFERENCES dbo.Table3
    (T3_PK)
    GO
    --Create a basic view to select some data
    CREATE
    VIEW dbo.AliasView1
    AS
    select
    t2.T2_FK as Table2_ForeignKey,
    t1.T1_Field1 as Table1_FieldOne,
    t2.T2_Field1 as Table2_FieldOne
    FROM Table1 t1
    Left outer
    join Table2 t2 on t2.T2_FK
    = t1.T1_PK;
    GO
    --Create another view that select basic data, and also selecting data from view 1
    CREATE
    VIEW dbo.AliasView2
    AS
    select
    v1.Table1_FieldOne
    as Table1_FieldOne,     
    v1.Table2_FieldOne
    as Table2_FieldOne,  
    t3.T3_Field1 as Table3_FieldOne,
    t3.T3_Field2 
    FROM Table3 t3
    Left outer
    join AliasView1 v1 on v1.Table2_ForeignKey
    = t3.T3_PK;
    GO
    --My attempt to get the desired output, but no luck
    SELECT 
    col.COLUMN_NAME as AliasColumnName, col.DATA_TYPE, col.CHARACTER_MAXIMUM_LENGTH
    as max_length, colu.*
    FROM
    information_schema.COLUMNS col
    left
    outer join
    (SELECT 
    VIEW_SCHEMA, VIEW_NAME, COLUMN_NAME,
    min(TABLE_NAME)
    as TABLE_NAME
    FROM information_schema.VIEW_COLUMN_USAGE colu
    WHERE VIEW_NAME =
    'AliasView2'
    Group by VIEW_SCHEMA, VIEW_NAME, COLUMN_NAME
    ) COLU ON colU.VIEW_NAME
    = col.TABLE_NAME
    and colu.COLUMN_NAME
    = col.COLUMN_NAME
    left
    outer join
    (select a.name
    as TableName, c.name
    as FieldName
    from sys.foreign_key_columns fk
    join sys.all_objects a
    on a.object_id
    = fk.parent_object_id
    join sys.all_columns c
    on c.object_id
    = a.object_id
    and c.column_id
    = fk.parent_column_id
    join sys.all_objects ar
    on ar.object_id
    = fk.referenced_object_id
    join sys.all_columns cr
    on cr.object_id
    = ar.object_id
    and cr.column_id
    = fk.referenced_column_id
    join sys.schemas scr
    on scr.schema_id
    = ar.schema_id
    ) fks on fks.TableName
    = colu.TABLE_NAME
    and fks.FieldName
    = colu.COLUMN_NAME
    WHERE COL.TABLE_NAME
    = 'AliasView2'
    order
    by col.ORDINAL_POSITION
    This is the results being returned: (That is not 100% what I am looking for)
    AliasColumnName
    DATA_TYPE
    max_length
    VIEW_SCHEMA
    VIEW_NAME
    COLUMN_NAME
    TABLE_NAME
    Table1_FieldOne
    varchar
    1
    dbo
    AliasView2
    Table1_FieldOne
    AliasView1
    Table2_FieldOne
    varchar
    1
    dbo
    AliasView2
    Table2_FieldOne
    AliasView1
    Table3_FieldOne
    varchar
    1
    NULL
    NULL
    NULL
    NULL
    T3_Field2
    varchar
    1
    dbo
    AliasView2
    T3_Field2
    Table3
    The desired results must be like the following:
    AliasColumnName
    DATA_TYPE
    max_length
    VIEW_SCHEMA
    VIEW_NAME
    COLUMN_NAME
    TABLE_NAME
    Table1_FieldOne
    varchar
    1
    dbo
    AliasView2
    T1_Field1
    Table1
    Table2_FieldOne
    varchar
    1
    dbo
    AliasView2
    T2_Field1
    Table2
    Table3_FieldOne
    varchar
    1
    dbo
    AliasView2
    T3_Field1
    Table3
    T3_Field2
    varchar
    1
    dbo
    AliasView2
    T3_Field2
    Table3
    NOTE:  the COLUMN_NAME and TABLE_NAME must the REAL field of the TABLE it belongs to and not only ONE LEVEL Higher’s ALIAS View Name

    Now we have a lot of views which select data from the tables, but I need to get the "Table Column Name" that is linked in the view.
    If you are using SQL Server 2012/2014, then you can use
    sys.dm_exec_describe_first_result_set (Transact-SQL) to gte the informations.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

Maybe you are looking for