query table with dynamic table name is it possible?

  • Maybe what I try to do is a bit weird, but my thought there should be a way to do it without first building sql string, then run with EXEC statement.

    if the statement below, guaranty to return a table name of something like "Prefix_101_Suffix"

    SELECT OBJECT_NAME(

    OBJECT_ID('Prefix'+ cast(@someIntParameter as varchar(10) +'_Sufix')

    ) AS T1

    Why shouldn't the following work?

    SELECT * FROM (

    OBJECT_ID('Prefix'+ cast(@someIntParameter as varchar(10) +'_Sufix')

    ) AS T1

    --or

    UPDATE T1

    FROM (SELECT OBJECT_NAME(

    OBJECT_ID('Prefix'+ cast(@someIntParameter as varchar(10) +'_Sufix')

    ) AS T1

    SET SET T1.SOMECOLUMN=@SOMEVAVLUE

    thanks for looking into this.

  • Nope. SQL doesn't work that way.

    Look into sp_executeSQL for a better way to do this than EXEC(), but you'll need to use dynamic SQL for that kind of thing.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

  • Got You! I have been using sp_executeSql, Just want to see if there is a way that I dont know of.

    thanks!

    GSquared (10/25/2012)


    Nope. SQL doesn't work that way.

    Look into sp_executeSQL for a better way to do this than EXEC(), but you'll need to use dynamic SQL for that kind of thing.

Viewing 3 posts - 1 through 2 (of 2 total)

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