實用的存儲過程之二
2024-07-21 02:09:00
供稿:網友
實用的存儲過程之二
筆者工作的公司采用的是sqlserver數據庫,每天都要處理大量的數據,由于筆者進公司的時間比較晚,公司現有的大部分的程序都是以前的程序員留下的,因為他們沒有相關的文檔,筆者對于后臺數據庫的很多表的結構和數據都不甚了解,給日常的維護造成了很大的麻煩。
在對后臺數據庫進行研究的過程中,我需要得到數據庫的某些相關信息,比如,公司的數據庫中有幾個表存放筆者的個人資料,像人事表、工資表、部門表等等,但具體是哪些表,就不是很清楚了,如果要一個一個表地找,可能天亮了也找不完,所以我決定做一個通用的存儲過程,能對當前數據庫所有字符型字段進行遍歷,找出精確匹配含有要查找字符串的表和字段,并且羅列出來。比如,人事表的name字段,工資表的salary_name字段,部門表的employe_name字段都有筆者的名字,我希望能把這些找出來。存儲過程如下:
if exists (select name from sysobjects
where name = 'searchname' and type = 'p')
drop procedure searchname
go
create procedure searchname @sname varchar(10)
as
begin
create table #tablelist(
tablename char(200),
colname char(200)
)
declare @table varchar(200)
declare @col varchar(200)
set nocount on
declare curtab scroll cursor for select name from sysobjects where xtype='u'
open curtab
fetch next from curtab into @table
while @@fetch_status=0
begin
declare curcol scroll cursor for select name from syscolumns where (xtype=175 or xtype=167) and (id in (select id from sysobjects where [email protected]))
open curcol
fetch next from curcol into @col
while @@fetch_status=0
begin
execute('insert into #tablelist select '''[email protected]+''','''[email protected]+''' from '[email protected]+' where '[email protected]+'='''[email protected]+'''')
fetch next from curcol into @col
end
close curcol
deallocate curcol
fetch next from curtab into @table
end
close curtab
deallocate curtab
set nocount off
select distinct * from #tablelist
drop table #tablelist
end
調用很簡單,如想找筆者的名字,調用searchname ‘forgot2000’即可,查找速度視乎當前數據庫的大小而定。希望這個存儲過程能對大家有所幫助吧。本人e-mail:[email protected],qq:33563255,希望能跟大家共同交流,謝謝!
本存儲過程在sqlserver7.0/2000下通過。
,歡迎訪問網頁設計愛好者web開發。