Erland,
I tried several variations of what you suggested and every time I was
faced with the same problem. No matter which way I went about it there
was always something essential part of your process that was out of
scope somehow.
I did come up with a working solution although I'm not sure how much I
like it. I'll post the code below just in case you are interested:
create table #new_record_set (dummy_column int null)
set @sql_script_for_table_structure = ' select top 0 * into
#for_structure_only from openrowset(' + char(39) + @provider_name +
char(39) + ',' + char(39) + @datasource + char(39) + ';' + char(39) +
@user_id + char(39) + ';' + char(39) + @password + char(39) + ',' +
char(39) + @query_string + char(39) + ') ' + char(13) +
' declare @object_id int ' + char(13) +
' declare @sql_string nvarchar(4000) ' + char(13) +
' set @object_id = (select object_id(' +
char(39) + 'tempdb.dbo.#for_structure_only' + char(39) + ')) ' +
char(13) +
' declare @current_column_order int ' + char(13) +
' set @current_column_order = 0 ' + char(13) +
' declare @max_column_order int ' + char(13) +
' set @max_column_order = (select max(colorder) from
tempdb..syscolumns where id = @object_id)
while (@current_column_order <> @max_column_order)
begin
set @current_column_order = @current_column_order + 1
set @sql_string = (select ''alter table #new_record_set
add '' + a.name + '' '' + b.name +
(case b.name
when ''int''
then '' null''
when ''bigint''
then '' null''
when ''datetime''
then '' null''
when ''bit''
then '' null''
else '' ('' + convert(nvarchar,a.length) + '')
null''
end)
from tempdb..syscolumns a inner join
tempdb..systypes b on
a.xtype = b.xtype
where a.id =
object_id(''tempdb.dbo.#for_structure_only'')
and a.colorder = @current_column_order and b.name
<> ''sysnames'')
exec sp_executesql @sql_string
end'
exec sp_executesql @sql_script_for_table_structure
alter table #new_record_set drop column dummy_column
I'm not sure how the formatting will appear once this is posted. I
apologize if it is unreadable. Basically I build an sql script that
executes openrowset into a temp table within the scope of the dynamic
sql. I then alter a table created in the main procedure to include the
exact column names and data types of my openrowset record set. The table
built with the scope of the dynamic sql is lost but I still have the
altered table from my main procedure.
Thanks for your help!
Cliff
*** Sent via Developersdex
http://www.developersdex.com ***