Results 1 to 3 of 3

Thread: Table Name In A Variable

  1. #1

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Question Table Name In A Variable

    Is it possible to declare and use a table name please. I am trying to get this type of query to run, but cannot find the right syntax:
    Code:
    DECLARE @TableName nvarchar 
    
    IF @MyPassedInBitVariable = 0 
    	SET @TableName = [MyDB..MyTableName1]
    ELSE 
    	SET @TableName = [MyDB..MyOtherTableName2] 
     
    
    SELECT  @TableName.Column1  
    FROM 	@TableName
    Thanks!

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  2. #2
    Fanatic Member kaffenils's Avatar
    Join Date
    Apr 2004
    Location
    Norway
    Posts
    946

    Re: Table Name In A Variable

    Quote Originally Posted by alex_read
    Is it possible to declare and use a table name please. I am trying to get this type of query to run, but cannot find the right syntax:
    Code:
    DECLARE @TableName nvarchar 
    
    IF @MyPassedInBitVariable = 0 
    	SET @TableName = [MyDB..MyTableName1]
    ELSE 
    	SET @TableName = [MyDB..MyOtherTableName2] 
     
    
    SELECT  @TableName.Column1  
    FROM 	@TableName
    Thanks!
    No, not the way you do it here. One way to solve the problem is to assign the table name to the @TableName variable and then build a TSQL statement into another variable that you execute with sp_executesql. You could also execute the SELECT statements directly in the IF...ELSE code.

  3. #3

    Thread Starter
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538

    Re: Table Name In A Variable

    Ok, yeah I found examples of those thanks, was just wondering if I could do it in that way. Oh well, thanks for clearing that up for me, cheers!

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width