Reference Query within a Query

  • Hi everyone

    This is definitely a rookie question.  In Access, I can reference another query by just using its name.  I tried to do the same thing in SQL Server and I got an error.  Here is my query:

    SELECT *

    FROM QRY_DATES

    The message I got was

    Msg 208, Level 16, State 1, Line 1

    Invalid object name 'QRY_DATES'.

    Completion time: 2021-11-15T13:02:46.9010455-08:00

    How exactly do I reference qry_dates within the query I wrote above? Again, sorry for the rookie question.

    Thank you

     

  • .

    • This reply was modified 3 years ago by  water490.
  • Pretty sure in SQL Server, that would be a view or a table.

    You cannot name a query.  So whatever the contents of the query "QRY_DATES" are, you would need to toss into a VIEW and then you should be able to SELECT from it.

    The above is all just my opinion on what you should do. 
    As with all advice you find on a random internet forum - you shouldn't blindly follow it.  Always test on a test server to see if there is negative side effects before making changes to live!
    I recommend you NEVER run "random code" you found online on any system you care about UNLESS you understand and can verify the code OR you don't care if the code trashes your system.

  • First Create your query as a VIEW:

    CREATE VIEW dbo.QRY_DATES AS

    SELECT ...

    Once the view is in place, you can reference it from other queries.

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • The Pedant in me yells back Common Table Expression.

    Technically a CTE is a named query.  But it is probably not in the context of the OP question

Viewing 5 posts - 1 through 4 (of 4 total)

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