Tuesday, April 26, 2011

store procedure for searching particlaur table all the table have a access rights from the SQL Server

create Procedure Sp_CTSI_internal
@start_date nvarchar(50),
@end_date nvarchar(50)
as
declare @count_database int
declare @inc_count int
declare @name_database nvarchar(4000)
declare @sql_query nvarchar(4000)
declare @table_name nvarchar(4000)
declare @report_path nvarchar(4000)
declare @get_query nvarchar(4000)
declare @query nvarchar(4000)
--declaration end

EXEC('Create table internal_ctsi_result(Custno nvarchar(100),Total_Count int,Database_Name nvarchar(1000))')
--initialize the value for the varibales
set @inc_count=5
set @table_name='[master].[CTSI\Vijay].internal_ctsi_result'
select @count_database=count(dbid) from sql4.master.dbo.sysdatabases

--End of Initialization

while(@inc_count<=@count_database)
begin
select @name_database=name from sql4.master.dbo.sysdatabases where dbid=@inc_count and ISNULL(HAS_DBACCESS ([Name]),0)=1 order by [Name]
if exists(select top 1 name from sql4.master.dbo.sysdatabases where dbid=@inc_count and ISNULL(HAS_DBACCESS ([Name]),0)=1 order by [Name])
begin

--begin exec
exec('
declare @sql nvarchar(4000)
declare @sql_query nvarchar(4000)
use '+@name_database+'
if exists(select TOP 1 table_name from information_schema.tables where table_catalog='''+@name_database+''' and table_name=''shipment'' and table_type=''base table'')
begin
--print ''tables Exists in the Database :''+'''+@name_database +'''
if exists(select top 1 column_name from information_schema.columns where table_catalog='''+@name_database+''' and table_name=''shipment''  and column_name=''entdate'')
begin
set @sql=''insert into '+@table_name+'(Custno,Total_Count,Database_Name) select custno,count(*)as Total_count,'''''+@name_database+''''' from  sql4.'+@name_database+'.dbo.shipment where entdate between ''''1/1/2010'''' and ''''12/31/2010'''' group by custno''
exec(@sql)
print @sql
end
end
')
--end exec

end
set @inc_count=@inc_count+1
end
exec('use master')
--Export report ot Excel
--set @get_query='select * into sql4.[MASTER].[CTSI\Vijay].temp# from [master].[CTSI\Vijay].internal_ctsi_result'
set @query='select * from SQL4.[MASTER].[CTSI\Vijay].internal_ctsi_result'
exec(@query)
drop table [master].[CTSI\Vijay].internal_ctsi_result
go



Run the Procedure
exec sql4.[master].[CTSI\Vijay].Sp_CTSI_internal '1/1/2010','12/31/2010'



No comments: