x

Need to use the contents of a field in a table select

Need to use the contents of a field as a table select. For example, my table (ATest) contains a field name (selection_id). The contents of the field contains a table name (selection_12345) that I need to query to obtain the contents of selection_12345. How can I pass the contents as a table name in another select?

Example:
Query --- select * from ATest

Result ---
selection_id (column)
selection_12345 (column contents)

I'm trying to do a select * from selection_12345 by passing the selection_id contents as a variable.

more ▼

asked Aug 07, 2012 at 06:53 PM in Default

laurscho gravatar image

laurscho
0 1 1

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

If you only return a single row, you can set a variable like this:

DECLARE @MyVariable nvarchar(255);
SELECT @MyVariable = TableName
FROM ATest;

Then, you would have to create a dynamic T-SQL statement to execute the second query:

DECLARE @MySQL nvarchar(max);
SET @MySQL = 'SELECT * FROM ' + @MyVariable;
sp_execute @MySQL;

Those are examples. You would want to be careful to ensure you can't get SQL Injection

more ▼

answered Aug 07, 2012 at 07:24 PM

Grant Fritchey gravatar image

Grant Fritchey ♦♦
98k 19 21 74

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x38
x20

asked: Aug 07, 2012 at 06:53 PM

Seen: 470 times

Last Updated: Aug 07, 2012 at 08:05 PM