Here is what I'm trying to accomplish. I am creating a dynamic table value reading script. I only need to read and collect specific values in each of the tables.

  1. Collect the tables #xPropTableListTempTable
  2. Loop through each table and collect the required columns #xPropColumnListTempTable Every thing works but the last step.... Collecting the values from each table Issue

Tables

  1. I don't how many tables are used to support the capability.
  2. I do know the naming pattern of the tables: XPROPERTYVALUES, XPROPERTYVALUES1, XPROPERTYVALUES2, ....
  3. I can get a list of the table text names from the view information_schema.tables
  4. I can insert the Table names into a local temp #table to iterate through

Columns

  1. In each table I do not know the number of columns.
  2. I do know the naming pattern of the columns I need: '%$is_Defined'
  3. I can get a list of the columns names from the view information_schema.columns
  4. I can insert the columns names into a local temp #columns to iterate through

Issue

Dynamically Collecting the values from each table

I can't create a temp #table, or instantiate a table object, using the table text names.

I did try and did not work:

Declare @tempTableCreateStr as nVarchar(max)
set @tempTableCreateStr = 'Select * Into #xPropValueTempTable From ' + @tableName + ' Where item_id = ''' + @itemGUID + ''''
Print @tempTableCreateStr
Exec sp_executesql @tempTableCreateStr

But then I read a post that stated that Exec can not perform the Select Into function. So I can't perform this step:

SELECT @propertyValue = STUFF((Select ', ' + @propertyName 
                From  
                  (Select @propertyName, ROW_NUMBER() Over(Order By property_value_column) as Row  
                   From #xPropValueTempTable  
                  ) as TMP3 
                for xml path('')),1,1,'')

Also tried:

TSQL select into Temp table from dynamic sql

--Set @tempTableViewCreateStr = 'Select * Into #xPropValueTempTable From ' + @tableName + ' Where item_id = ''' + @itemGUID + ''''
--Set @tempTableViewCreateStr = 'Create View xPropValueTempView Select * From ' + @tableName + ' Where item_id = ''' + @itemGUID + ''''
Set @tempTableViewCreateStr = 'Create View xPropValueTempView Select * From ' + @tableName 
Print @tempTableViewCreateStr
Exec (@tempTableViewCreateStr)

Select * Into #xPropValueTempTable From xPropValueTempView --Where item_id = @itemGUID
Drop View xPropValueTempView

Error

In Table:[xp].XPROPERTYVALUES
Create View xPropValueTempView Select * From [xp].XPROPERTYVALUES
Msg 156, Level 15, State 1, Procedure xPropValueTempView, Line 1 [Batch Start Line 0]
Incorrect syntax near the keyword 'Select'.
Msg 208, Level 16, State 1, Line 56
Invalid object name 'xPropValueTempView'.
0

There are 0 best solutions below