devxlogo

Problem with Select Statement

Question:
I’m writing a select statement to make a table name a variable whose value is set according to a condition:

Var tablename;tablename := emp tableselect * from tablename;

But I get an error message. How do I make this statement work?

Answer:
Your syntax is close to what you need. But you need to call the EXECUTE command with the SQL string. Here’s code you can run in Query Analyzer that uses a variable for the table name and retrieves all the records from the Employees table:

DECLARE @TableName varchar(255)SET @TableName = 'Employees'EXEC ('SELECT * FROM ' + @TableName)

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.