x
login about faq Site discussion (meta-askssc)

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 '12 at 06:53 PM in Default

laurscho gravatar image

laurscho
0

(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 '12 at 07:24 PM

Grant Fritchey gravatar image

Grant Fritchey ♦♦
62.3k 12 20 66

(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.

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



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x25
x17

asked: Aug 07 '12 at 06:53 PM

Seen: 171 times

Last Updated: Aug 07 '12 at 08:05 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.