Table Name as Parameter

  • Hi All,

    Its my first time here!!! Hope someone can help me with this problem... Can we use the table name as parameter?

    Example:

    Declare @TableName as Varchar(20)

    Begin

         Select count(*) From @TableName

    End

    Any help will do...

    Thanks,

    Aris

     

     

  • Welcome here!

    You asked a FAQ which is best explained here:

    http://www.sommarskog.se/dynamic_sql.html

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • This can be done but the query generated will be dynamic and has to be exceuted using the Execute Command

    for eg:

    if you want to retrieve the count from a table

    execute( 'Select count(*) From ' + @TableName )

    this has to be executed as mentioned above


    Kindest Regards,

    Sureshkumar Ramakrishnan

  • Thanks to both of you!!! I got what I wanted...

  • Joe, Joe, Joe tsk, tsk.  Pretty damn rude addressing somebody self titled "Newbie!".  Maybe some book recommendations would have been more productive.

    To you I say:

    Refer to item 2.  You have no idea what you are doing (at least not entirely).

    There is a very good case for, how do you say "use slow, proprietrary dynamic SQL to kludge a query together on the fly" (maybe or maybe not in Newbie's case).  Though I am not sure what you mean by proprietary.

    Take a query that is passed parameters for determining results.  The query plan can differ drastically based on the parameters passed.  It is at times very much faster to use slow, proprietary [still not sure of your meaning] dynamic SQL to run the query with an optimized plan.

    Your remarks are general in nature yet speak of performance problems.  Peak performance requires on to following rules in a general nature and venture outstide them to get the best performance. 

    Oh yeah, where'd you get the one-year-in-production rule?  This is sure to piss you off and you are welcome to vent.  I will not pain everybody else in the forum, however, with a reply to any blithering and simple minded post.

    Yours truly,

    Mike

     

     

     

     

     

     

     

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

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