Question

Can I use a variable as the name of an existing table? The first SELECT works fine, but the second generates an error suggesting I am trying to create a table variable. All I want though is to use a variable for the name of an existing table.

declare @name varchar(100)

CREATE TABLE CURVES( 
    ARC VARCHAR(10),
    RADIUS VARCHAR (10),
    CENPTid BIGINT,
    StartPTid BIGINT,
    EndPTid BIGINT)

INSERT INTO CURVES  
VALUES ('10.23', '50.22', 5, 6, 8)

SELECT * FROM CURVES
set @name='CURVES'
SELECT * FROM @name
Was it helpful?

Solution

This is dynamic SQL approach, so

set @name='CURVES'
exec ('SELECT * FROM '+ @name)

OTHER TIPS

You cannot do what your trying to do this way.

But you can Declare a Table Variable and then populate that table variable and select from that table variable. something like this...

-- Actual Table 

CREATE TABLE CURVES
( 
 ARC VARCHAR(10),
 RADIUS VARCHAR (10),
 CENPTid BIGINT,
 StartPTid BIGINT,
 EndPTid BIGINT
)
GO

-- Populate the table 

INSERT INTO CURVES  
VALUES ('10.23', '50.22', 5, 6, 8)
GO


-- Declare the table Variable 

declare @name TABLE 
(
 ARC VARCHAR(10),
 RADIUS VARCHAR (10),
 CENPTid BIGINT,
 StartPTid BIGINT,
 EndPTid BIGINT
)


INSERT INTO @name     --<-- Populate the Table Variable
SELECT * FROM CURVES

SELECT * FROM @name  --<-- Now select from table Variable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top