SSMS 2012: Using CTE in a query - Invalid column name 'EmployeeID' !!??

Hi all,
From Page 88 of the Book "SQL Programming & Database Design Using Microsoft SQL Server 2012" written by Kalman Toth, I copied the following code of Using CTE in a query:
-- CTETest2.sql /// saved in C:\My Documents\SQL Server Management Studio\
----Page 88 of Book by Toth === Using CTE in a query ----- 13 March 2015
--Using CTE in a query
;WITH CTE (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS (SELECT SalesPersonID, COUNT(*), CONVERT(date, MAX(OrderDate))
FROM Sales.SalesOrderHeader GROUP BY SalesPersonID )
--Start of outer (main) query
SELECT E.EmployeeID,
OE.NumberOfOrders AS EmpOrders,
OE.MostRecentOrderDate AS EmpLastOrder,
E.ManagerID,
OM.NumberOfOrders AS MgrOrders,
OM.MostRecentOrderDate AS MgrLastOrder
FROM HumanResources.Employee AS E
INNER JOIN CTE AS OE ON E.EmployeeID = OE.SalesPersonID
LEFT OUTER JOIN CTE AS OM ON E.ManagerID = OM.SalesPersonID
In my SQL Server 2012 Management Studio, I executed this set of code and I got the following fatal error:
Msg 207, Level 16, State 1, Line 16
Invalid column name 'EmployeeID'.
I have no clues why I got this error message in this .sql trial of my second practice in doing CTE.  Please kindly help and let me know where I made mistake and how to resolve this problem.
Thanks in advance,
Scott Chang

Hi scott_morris-ga, Thanks for your nice response.
I changed EmployeeID to BusinessEntityID as you pointed out and executed the revised code:
-- CTETest2.sql /// saved in C:\My Documents\SQL Server Management Studio\
----Page 88 of Book by Toth === Using CTE in a query ----- 13 March 2015
--Using CTE in a query
;WITH CTE (SalesPersonID, NumberOfOrders, MostRecentOrderDate)
AS (SELECT SalesPersonID, COUNT(*), CONVERT(date, MAX(OrderDate))
FROM Sales.SalesOrderHeader GROUP BY SalesPersonID )
--Start of outer (main) query
SELECT E.BusinessEntityID,
OE.NumberOfOrders AS EmpOrders,
OE.MostRecentOrderDate AS EmpLastOrder,
E.ManagerID,
OM.NumberOfOrders AS MgrOrders,
OM.MostRecentOrderDate AS MgrLastOrder
FROM HumanResources.Employee AS E
INNER JOIN CTE AS OE ON E.BusinessEntityID = OE.SalesPersonID
LEFT OUTER JOIN CTE AS OM ON E.ManagerID = OM.SalesPersonID
I got 2 new error messages:
Msg 207, Level 16, State 1, Line 17
Invalid column name 'ManagerID'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'ManagerID'.
I have no ideas what should be used to replace 'ManagerID' in my revised code. Could you please help again and give me the right thing to replace the 'ManagerID'? By the way, where in the AdventureWorks do you find the right things?  Please enlighten
me in this matter.
Many Thanks again,  Scott Chang 

Similar Messages

  • Using "$" character with Oracle; getting "invalid column name"

    I am running the following query against an Oracle database:
    select price from my_table
    where index_name = 'CGPR_C$'
    and settlement_date = to_date('02/19/2001','MM/DD/YYYY')
    The query runs fine in TOAD.
    If I run this query from my java code, I get an "invalid column name" exception.
    If I take out the "$" character, the query runs fine.
    I've tried inserting the "$" in as unicode, escaping out the character, ||chr(36)||, and nothing works.
    Please help!
    Ashley

    Look up your Oracle SQL documentation and find out how to use column names that would otherwise be invalid. Some databases allow you to put column names, table names, and so on in square brackets (e.g. [CGPR_C$]) but I don't know Oracle's syntax.

  • Invalid column name in query string - using Format function

    In my post just before this one the problem was solved for writing a query string using a date range. The rest of the query string includes the same date field (Call_Date) but formatted as 'MMM-YY'. I get an invalid column name error when I add this field to the query string. Here is the rest of the query string:
    strSql = "SELECT Format(CALL_DATE,'mmm-yy'), " _
    & "HOME_REGION FROM CCC2.CASE_EPRP " _
    & "WHERE (HOME_REGION = 'NCR') AND " _
    "(CALL_DATE >= to_date( '1/1/2002', 'MM/DD/YYYY' )" _
    & "AND CALL_DATE <= to_date( '2/28/2003', 'MM/DD/YYYY' ))"
    In the Access Query tool I can include this field
    Format(CALL_DATE,'mmm-yy')
    and the query runs fine (I just need to make it dynamic using ADO). But in my ADO query string above, I get the invalid column name error. Is there a way I can include
    Format(CALL_DATE,'mmm-yy')
    in my ADO query string? I appologize for not being more familiar with Oracle Sql. Any help greatly appreciated.
    Thanks again,
    Rich

    Thank you very much for your reply. I think I'm getting closer to the solution. Just I got an error message
    "date format not recognized"
    when I add "to_char( call_date, 'mmm-yy' )" to the query string. I tried using all uppercase, but that did not make a difference. Do I need to use to_date inside the to_char maybe?
    to_char(to_date(call_date, 'mmm/yy'), 'mmm-yy')
    Thanks again for your help.
    Rich

  • ORA-00904: invalid column name in select query by using abstract datatype

    Hi,
    I had created abstract datatype as PERSON_TY and ADDRESS_TY ,
    after inserting the record . i'm tryng to select the column but i got the error , even i refferd all those thing. they are given that same please look this finde me a result.
    SQL> DESC PERSON_TY
    Name Null? Type
    NAME VARCHAR2(25)
    ADDRESS ADDRESS_TY
    SQL> DESC ADDRESS_TY
    Name Null? Type
    STREET VARCHAR2(30)
    CITY VARCHAR2(25)
    STATE CHAR(2)
    COUNTRY VARCHAR2(15)
    SQL> SELECT * FROM EMPLOYE
    2 ;
    EMP_CODE
    PERSON(NAME, ADDRESS(STREET, CITY, STATE, COUNTRY))
    10
    PERSON_TY('VENKAT', ADDRESS_TY('112: BLUE MOUNT', 'CHENNAI', 'TN', 'INDIA'))
    20
    PERSON_TY('SRINI', ADDRESS_TY('144: GREEN GARDEN', 'THAMBARAM', 'TN', 'INDIA'))
    SQL> SELECT PERSON.NAME FROM EMPLOYE
    2 ;
    SELECT PERSON.NAME FROM EMPLOYE
    ERROR at line 1:
    ORA-00904: invalid column name
    regards
    venki

    SELECT PERSON.NAME FROM EMPLOYEIf you look in the documentation, you will see that we need to alias the table in order to make this work:
    select e.person.name from employees e
    /Cheers, APC
    Blog : http://radiofreetooting.blogspot.com

  • Use of NOT IN leads to an invalid column name error

    The query works just fine when placed directly into sql plus
    The query works, called from a Java using an Oracle Statement, ONLY IF I remove the NOT.
    However, with NOT it chokes, and gives me this:
    selQ=select lenum, zeugn from stock_rpt where lenum NOT in ('X12345', 'X23456')
    Could Select or Read Selected data
    java.sql.SQLException: Invalid column name
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
    at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3319)
    at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:1926)
    at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:1515)
    at ecspack.StockRpt.selRecsByQ(StockRpt.java:172)
    at ecspack.StockRpt.selByDiff(StockRpt.java:261)
    at teste.main(teste.java:40)
    The column does have an index.
    The above is my simplified test query, I am using to narrow down the problem.
    SelQ is the value of the Select String.
    Really I want to do something like this:
    select x1, x2 from tableX where x1 NOT IN (select y1 from tableY)
    I know I can just compare records one at a time, but I would rather not, if there is a way to make NOT IN work.
    Thank you

    Hi Eileen Keeney ,
    may be you can use prepared statement but beware of sql injection
    selQ=select lenum, zeugn from stock_rpt where lenum NOT in ('X12345', 'X23456')
    Try :
    selQ=select lenum, zeugn from stock_rpt where lenum NOT in (?, ?)
    Then try running it with this fixed parameter binding:
    prest.setString(1, "X12345");
    prest.setString(2, "X23456");

  • Using oracle thin driver with to_char gives invalid column name

    select x,y,z, to_char(event_time,'YYYY-MMM-DD') from eventtable;
    if i execute the above query using oracle thin driver it gives me invalid column name. It works fine if i use weblogic driver. So what could be the problem ???
    thanks.

    Sorry , forgot to add that 'YYYY-MM-DD' or 'YYYY-Month-DD' or 'Year-MM-DD' or 'Year-Month-DD' are also allowed(please cheek also for other combinations), not 'YYYY-MMM-DD'.
    Thanks

  • "invalid column name" using resultset.getString()???

    I had a sql query against oracle db:
    select table1.field1, table1.field2, table2.field3
    from table1, table2
    where table1.field1=table2.field1;
    i got a valid resultset and i can enum the resultset by rs.getString(colnum). However, when i try to use rs.getString(table1.field1), i get a sql exception: "invalid column name". has anybody seen this before?
    TIA

    Hi,
    You can also modify your query and use the keyword "As" to give your fields another name :
    select user.name as userName, admin.name as adminName
    from user, admin
    rs.getString("userName");
    rs.getString("adminName");

  • Error querying fact: -2417217900 invalid column name

    Dear Xperts
    while validating script logic it gives error"error querying fact: -2417217900 invalid column name P_ACCT"
    P_ACCT dimension created by me.
    problem has started today while creating new script logic.
    as old logic created earlier was sucessfully validated
    new logic was created refering document 330 for bpc,so there is no scripting error
    pls guide me through this.
    thanks
    kashyap

    thanks  for ur advice
    i was able  to validate logics previously.
    i tried way you sugested but was unable to validate.
    i also  tried updating that dimension members but it was giving me some olap querry error while processing dimension after changing dimension members.
    so finally i deleted that dimension created new one did whole process again
    & was successfull
    but i wanted to know why this error could have occured
    thanks
    kashyap

  • Invalid column name 'xml_index_type'

    Hi, 
    I'm not sure when this started happening but today, none of us using SSMS 2012 connected to SQL server 2012 SP1 were able to script any objects.  we are presented with the message
    Failed to retrieve data for this request. (microsoft.sqlserver.management.sdk.sfc)
    Invalide column name 'xml_index_type'.
    see screenshot.
    wondering if any ran into this before and have a fix?
    Thanks

    @ Balmukund,
    all I'm doing is connecting to my 2012 sp1 instance on via my local SSMS, expand a database, and expand the table hive, right click on a table, and tell it to script the table to
    a new query window, clipboard, etc ... all give off that same error message.
    @wbob
    My SSMS client is a 2012 SP1 as I have a local dev instance on my box.  I use only the 2012 client to manage both sql server 2008 r2 and 2012:
    Microsoft SQL Server Management Studio 11.0.3128.0
    Microsoft Analysis Services Client Tools 11.0.3128.0
    Microsoft Data Access Components (MDAC) 6.1.7601.17514
    Microsoft MSXML 3.0 6.0 
    Microsoft Internet Explorer 9.10.9200.16576
    Microsoft .NET Framework 4.0.30319.296
    Operating System 6.1.7601
    On the server:
    Microsoft SQL Server Management Studio 11.0.3000.0
    Microsoft Analysis Services Client Tools 11.0.3000.0
    Microsoft Data Access Components (MDAC) 6.1.7601.17514
    Microsoft MSXML 3.0 6.0 
    Microsoft Internet Explorer 9.0.8112.16421
    Microsoft .NET Framework 4.0.30319.296
    Operating System 6.1.7601
    I just looked thru the sql log again for the upgrade and see no errors.  I would post it here but it is a long and boring read.
    In addition, in tools --> options --> SQL server object explorer --> scripting.  This is set to SQL server 2012 for 'script for server version'

  • Invalid column name error

    Having an interesting problem with a site I'm fixing. I'm
    sure I'm looking past the obvious, so maybe some of you can help:
    ASP Pages display results from recordset based on a session
    variable (memberID) that is created during user login.
    Recordset looks like this:
    <%
    Dim rs__MMColParam
    rs__MMColParam = "%"
    If (Session("memberID") <> "") Then
    rs__MMColParam = Session("memberID")
    End If
    %>
    <%
    set rs = Server.CreateObject("ADODB.Recordset")
    rs.ActiveConnection = MM_cnConnection_STRING
    rs.Source = "SELECT id, adminusername, anotherone1,
    anotherone2, anotherone3 FROM dbo.basic1 WHERE adminusername = '" +
    Replace(rs__MMColParam, "'", "''") + "'"
    rs.CursorType = 0
    rs.CursorLocation = 2
    rs.LockType = 3
    rs.Open()
    rs_numRows = 0
    %>
    Seems correct to me, unles I'm overlooking something obvious.
    Unfortunately I keep getting the following error:
    Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
    [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column
    name 'SESSIONVAR'.
    (Note: in this error above, SESSIONVAR is the name of the
    session variable memberID)
    Strange thing is, as long as the session variable is a #,
    everything works. If it's a word, it won't work. So it appears the
    session variables are being defined and passed to the next page.
    As for the database, it's a SQL Database
    column 'adminusername' is a NVARCHAR with a 4000 char limit
    Thanks in advance for any help.

    Are you sure the query is the same? It looks like the one you posted has a syntax error
    SELECT e.emp_id, e.dep_id
      FROM emp e, loc ct, dep dt
    WHERE[b] c.dep_id[/b] IN (SELECT dt.dep_idYou've aliased the LOC table to CT in the FROM clause, but you're using the alias C in the WHERE clause. You use the correct alias CT in the query in your IN clause.
    Justin

  • Invalid column name (with ojdbc)

    hi,
    I created a resultSet by executing query with more then one table in it. (left join)
    and now i want to getObject. so I execute resultSet.getObject("tablename.columnName")
    and I get this error "invalid column name".
    when i'm doing the same thing with MySQL it works fine.
    I don't want to do aliases for all the columns because there are too much of those.
    please help.
    thanks,
    asaf.

    that's not standard JDBC. You must use either the plain column name,
    or the column number. In cases where there are multiple columns with
    the same name you must use the column number for all but the first
    column with the same name.
    Joe Weinstein

  • Invalid column name: get_column_index

    Salam 2all
    please help me to solve this problem
    i have this error
    Invalid column name: get_column_index
    when i execute this code
    rs = stmt.executeQuery("Select EmpNo,Name,Degree,Occupation,DomainNo,Signature from Employee where EmpNo='"+cno+"'");
    if (rs.next())
         emp.setText(rs.getString("EmpNo"));
         name.setText(rs.getString("Name"));
         degree.setText(rs.getString("Degree"));
         occ.setText(rs.getString("Occupation"));
         int index=SearchIndex(Integer.parseInt(rs.getString("DomainNo")));                    dom.setSelectedIndex(index);
         domn.setText(rs.getString("Signature"));
    By tracing the code using System.out.println("BBBBBBBB");
    i reach that the error is in the statment
    {     domn.setText(rs.getString("Signature"));
    but the spelling for"Signature" is the same, and i write it in the oracle creation table as follow
    create table Employee(
    EmpNo varchar(40) NOT NULL,
    Name varchar(40) NOT NULL,
    Degree varchar(4),
    Occupation varchar(4),
    DomainNo varchar(4),
    Signature varchar(40),
    primary key(EmpNo ),
    foreign key(DomainNo) references Cycle);
    Thanks 4 ur help
    Salam 2all

    'Signature' doesn't seem to be a reserved word in Oracle.
    First, I would try entering this query from a query tool. That may provide some clues.
    Next, I would try changing the column name to 'Signaturexxx' and see if it fixes the problem.
    This may be a bug in the driver.

  • Invalid column name - fixed by inserting a carriage return - Why?

    I'm writing some JSP pages and am executing a statement that retrieves values from three tables.
    When executing the statement I receive the error
    java.sql.SQLException: Invalid column name
    I just want to state here that ALL the column names are definitely correct. I attempted to isolate the problem using my SQL*Plus Interface.
    When copying and pasting the SQL that was used (I put the SQL statement into the HTML to allow me to do this) into SQL*Plus it also come up with the error. I found that if I broke up the statement it would run. Specifically if I placed a carriage return (by hitting enter) prior to the 'A' of the AND operator and then copied and pasted into SQL*Plus it would work!
    I thought the problem was related to bad syntax in the outer join operator. But removal of the outer join operator and making it a EQUI JOIN situation still gave the same results. I tried the use of brackets to 'help' the DB engine figure it out - silly I know, but it didn't work anyway :(
    I've tried this out on UNIX in SQL*Plus where the query was on one line and it worked fine. I've tried it on Oracle 8.1.5 SQL*Plus & Oracle 8.1.7 SQL*Plus on Win2000 and WinNT and no go.
    It has also been tested on an Oracle 7.3.4 DB and no go either.
    Remember I'm only using SQL*Plus to find out why it is not working - I'm actually attempting to execute this via JDBC (classes12.zip Oracle9 version) in my JavaBean. I can't place a carriage return to 'fix' the problem, and I'm assuming that I shouldn't either.
    I've pasted the SQL below (both non-working and working versions). I was going to paste the output of DESC on the associated tables should you too would rule out a mispelled column name, but I didn't want to put anyone off with a long post.
    If you can provide any advice I would be very appreciative.
    Darren James
    Show Me Technology
    SQL> SELECT UNIT.Asset_Number,Model,PERSON.Novell_User_Name FROM
    UNIT, UNIT_USERS, PERSON
    2 WHERE UNIT.Hardware_Reference_Number =
    UNIT_USERS.Hardware_Reference_Number(+) AND UNIT_USERS
    .Novell_User_Name = PERSON.Novell_User_Name (+) ORDER BY Make,
    Model, Asset_Number,Serial_Number,
    UNIT.Hardware_Reference_Number,Unit_Type,PERSON.Last_Name,PERSON.Fi
    rst_Name,PERSON.Novell_User_Name;
    3 /
    WHERE UNIT.Hardware_Reference_Number =
    UNIT_USERS.Hardware_Reference_Number(+) AND UNIT_USERS.Novel
    ERROR at line 2:
    ORA-00904: invalid column name
    REM -- Using the one with an return prior to the AND
    SQL> SELECT UNIT.Asset_Number,Model,PERSON.Novell_User_Name FROM
    UNIT, UNIT_USERS, PERSON
    2 WHERE UNIT.Hardware_Reference_Number =
    UNIT_USERS.Hardware_Reference_Number(+)
    3 AND UNIT_USERS.Novell_User_Name = PERSON.Novell_User_Name
    (+) ORDER BY Make, Model,
    4 Asset_Number,Serial_Number,
    5
    UNIT.Hardware_Reference_Number,Unit_Type,PERSON.Last_Name,PERSON.Fi
    rst_Name,PERSON.Novell_User_
    Name;
    ASSET_NUMBER
    MODEL
    NOVELL_USE
    10023445
    desktop raider
    tabisho
    10023445
    desktop raider
    pjblee
    100349864
    VEi8
    SQL>

    Ok. I feel ashamed that the answer was so simple and not the
    problem I thought it was. But in the interests of perhaps
    preventing someone else doing the same silly thing....
    The error was caused by using a wrong name when 'getting' the
    values int the return ResultSet object. (eg using getString
    ("s.Some_Name") when it should have been getString
    ("s.Another_Name").
    Interestingly the error did occur in one of our SQL*Plus
    versions. Why we still are not sure, but since this was a silly
    error on my part, I'm sure a similarly silly reason will be the
    cause there two.
    I appreciate those who responded though. It is a great resource.
    Darren James
    I'm just guessing here, but could it be some sort of a size thing? Could it be that, if you don't break up line 2, somehow
    it gets truncated or wrapped at an inappropriate place? To test
    this theory, you might try putting the carriage return in front
    of the ORDER BY, instead of in front of the AND, and see if it
    has the same effect. If you do get it figured out, please
    satisfy our curiosity and let us know.

  • Invalid Column Name message in the subquery

    Hi All, I am receiving the invalid column name message in the subquery. Please help me if there is any work around or change in the query:
    Sample query:
    update table1 set table1.column1 =
    (Select column1 from
    (Select column1 from table2 where
    table1.columnX = table2.columnX
    order by table2.columnM desc,table2.ColumnN desc,
    where rownum =1)
    When i run the above query i am receiving the following error message:
    ORA-00904:invalid column name at table1.columnx.
    This column is already existing in table1 and looks like this table is not recoginzed inside of the subquery.
    I am trying to update table1.column1 using the first value from table2 after ordering by table2.columnM desc, table2.columnN desc. (ColumnM and ColumnN are the Date columns which i need to perform the sorting). I am new to sql/Plsql. Thanks in Advance for help....

    The problem is that you can not refer to columns from the outer table from inside a second subquery inside your subquery. Only one level of subquery can be used to transport the column name,.
    A solution can be to use groups and aggregation functions instead of rownum = 1.
    The following might work.
    untested
    update table1
    set table1.column1 =
      (Select max(column1) keep (dense_rank first over table2.columnM desc,table2.ColumnN desc)
       from table2
       where table1.columnX = table2.columnX
       ) Another way can be to to make a UNCORRELATED subquery first and then filter on that uncorrelated query with the column name from the outer statement.
    This time I use a analytic function.
    untested
    update table1 u
    set u.column1 = (select v1.column1
       from
         (Select t2.column1, t2.columnX, row_number over (partition by t2.column1, t2.columnX order by t2.columnM desc,t2.ColumnN desc) as rn
          from table2
          ) v1
       where v1.columnX = u.columnX
       and v1.rn = 1
    where /* where clause is missing! */

  • Invalid column name in IMGSimilar

    Hi all,
    I have a question for the function IMGSimilar.
    I have a table musterbildsig, in which the generated signatures of 100 pictures are stored in the column msbild_sig. Each Signature in this table is to compare with all signatures in the column bild_signature of the table bildtable_intern_signature.
    I use the following java code.
    OracleResultSet rs_mbsig = (OracleResultSet) stmt.executeQuery("SELECT * FROM musterbildsig");
    while (rs_mbsig.next()){
    OrdImageSignature mbsig = (OrdImageSignature) rs_mbsig.getCustomDatum(2, OrdImageSignature.getFactory());
    String str = "SELECT bsig.bild_id, ORDSYS.IMGScore(1) AS Score FROM bildtable_intern_signature bsig WHERE ORDSYS.IMGSimilar(bsig.bild_signature, mbsig, 'color=\"0,7\" texture=\"0,5\" location=\"0,1\"', (float)th, 1) = 1 ORDER BY Score asc";
    OracleResultSet rs = (OracleResultSet) stmt.executeQuery(str);
    But i get the error message: invalid column name.
    I think, mbsig is wrong. But i don't know, how can i correct that?
    Please help!
    Thank you very much and greeting from germany!
    rabbit

    Hi,
    I think you aren't able to use "mbsig" directly in your query string. Instead you should substitute it with "?" as follows.
    String str = "SELECT bsig.bild_id, ORDSYS.IMGScore(1) AS Score FROM bildtable_intern_signature bsig WHERE ORDSYS.IMGSimilar(bsig.bild_signature, ?, 'color=\"0,7\" texture=\"0,5\" location=\"0,1\"', (float)th, 1) = 1 ORDER BY Score asc";
    After you have to declare, what "?" is by:
    OraclePreparedStatement stmt = (OraclePreparedStatement)conn.prepareStatement(str);
    stmt.setCustomDatum(1, mbsig);
    Now you can retrieve data with:
    OracleResultSet rs = (OracleResultSet) stmt.executeQuery();
    I hope it helps.
    greetings from germany :)
    Christian

Maybe you are looking for