0

apologies if this has been asked but my actual question is actually terribly difficult to query using search.

I have a table variable that I've created which constains the IDs, column names and table names of other tables such that an example row consists of

ID, Column, Table

2, AssetName, dbo.Asset

I now wish to insert into another table variable the results of a query which is composed of that row, for eg:

insert into @table2 .. 'select AssetName from dbo.Asset' [the results, specifically the AssetName column from the Asset table - perhaps 10 rows worth of data]

Please let me know how best to approach this.

1 Answer 1

1

You'll have to do that dynamically. For example, something like (untested):

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = N'INSERT INTO @Table2 SELECT ' + QUOTENAME(Column) + N' FROM ' + QUOTENAME(Table)
FROM   @Table1

EXEC sp_executesql @SQL

I'm not entirely sure if you don't need a global table variable for that (@@Table2).

Sign up to request clarification or add additional context in comments.

2 Comments

Or use a temp table that is declared prior to the dynamic sql.
I would note that you had to declare the table variable within the dynamic sql code for it to be recognised but regardless, in spite of my ignorance in this area this clearly seems like the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.