머.. 대충..
declare
@ip nvarchar(255)
, @db nvarchar(255)
, @schema nvarchar(255)
, @table nvarchar(255)
, @where nvarchar(500)
, @sql nvarchar(4000)
, @cols nvarchar(4000)
, @bdt nvarchar(30)
, @edt nvarchar(30)
, @top nvarchar(50)
if object_id('tempdb.dbo.#cols') is not null
drop table #cols
create table #cols(cols nvarchar(4000))
set @ip = '[192.168.0.1]'
set @db = '[customer]'
set @schema = '[dbo]'
set @table = '[account]'
set @top = 'top 10'
--set @top = ''
set @bdt = '20130311' --매개변수?
set @edt = '20130312' --매개변수?
set @bdt = convert(nvarchar(30), convert(datetime, @bdt), 121)
set @edt = convert(nvarchar(30), convert(datetime, dateadd(hh, 1, @edt)), 121)
set @where = 'regdate >= @bdt and regdate < @edt'
set @where = replace(@where , '@bdt', '''''' + @bdt + '''''')
set @where = replace(@where , '@edt', '''''' + @edt + '''''')
--컬럼리스트
set @sql ='
declare @cols nvarchar(4000)
set @cols = ''''
select @cols = @cols +
case
when ordinal_position = 1 then
case when collation_name is not null then column_name + '' collate Korean_Wansung_CI_AS '' + column_name else column_name end
else '','' + case when collation_name is not null then column_name + '' collate Korean_Wansung_CI_AS '' + column_name else column_name end
end
from ' + @ip + '.' + @db + '.information_schema.columns
where table_schema = ''' + replace(replace(@schema, ']', ''), '[', '') + ''' ' +
'and table_name = ''' + replace(replace(@table, ']', ''), '[', '') + '''
select @cols
'
insert #cols exec(@sql)
set @cols = (select top 1 cols from #cols)
--sql만들기
set @sql= 'select * from openquery(@ip, ''select @top @cols from @db.@schema.@table where @where'') t'
set @sql = replace(@sql, '@ip', @ip)
set @sql = replace(@sql, '@cols', @cols)
set @sql = replace(@sql, '@db', @db)
set @sql = replace(@sql, '@schema', @schema)
set @sql = replace(@sql, '@table', @table)
set @sql = replace(@sql, '@where', @where)
set @sql = replace(@sql, '@top', @top)
print @sql
print 'select top 10 ' + @cols + ' from ' + @ip + '.' + @db + '.' + @schema + '.' + @table