SQL Server 2008 SELECT * FROM @variable?

前端 未结 6 1314
旧时难觅i
旧时难觅i 2020-12-19 03:53

It is possible?

DECLARE @vTableName varchar(50)

SET @vTableName = (SELECT TableName FROM qms_Types WHERE Id = 1)

SELECT * FROM @vTableName
<
6条回答
  •  萌比男神i
    2020-12-19 04:11

    It seems as though different folks are interpreting the OP differently.

    I'm pretty sure the OP is asking for this type of concept / ability / maneuver...

    "Put a table name into a variable and then use that variable as though it were a table name."

    DECLARE @TableIWantRecordsFrom varchar(50)
    --      ^^^^^^^^^^^^^^^^^^^^^^
    
    SET @TableIWantRecordsFrom = (SELECT TableName FROM qms_Types WHERE Id = 1) -- (L1)
    --  ^^^^^^^^^^^^^^^^^^^^^^
    
    -- Let's say, at this point, @TableIWantRecordsFrom ... contains the text 'Person'
    --                           ^^^^^^^^^^^^^^^^^^^^^^
    
    -- assuming that is the case then...
    -- these two queries are supposed to return the same results:
    
    SELECT top 3 fname,lname,mi,department,floor FROM Person
    --                                                ^^^^^^
    SELECT top 3 fname,lname,mi,department,floor FROM @TableIWantRecordsFrom -- (L2)
    --                                                ^^^^^^^^^^^^^^^^^^^^^^
    

    From reading all the responses and answers, it appears that this kind of maneuver can't be done - unless - you use dynamic SQL which...

    • can be a bit of a pain to create and maintain and
    • can be more work to create than the time it "saves" you in the future.

    ================================================================

    There are other languages where this can be done... in literally, two lines of code (see (L1) and (L2) in above code) and not having to do a lot of formatting and editing.)

    (I've done it before - there is another language where all you'd need is L1 and L2...)

    ================================================================

    It is unfortunate that SQL Server will not do this without going to a decent amount of effort...

    • first write your SQL then
    • test it to make sure it does, in fact, work then
    • frame each line with tick marks and then escape your ticks that are now inside THOSE tick marks
    • declare the variable
    • set the variable to the sql statement you ticked above
    • (I may be missing some additional steps)
    • Oh, and then, if you ever need to maintain it
    •     you need to either, be very careful and just edit it right there, as is, and hope you get it all just right -or- you may have saved a copy of it... un-ticked and un-variablized so you can edit the "real" sql and then when you're done you can RE DO these steps... again.

提交回复
热议问题