sqlserver 全庫查詢 帶架構
阿新 • • 發佈:2017-09-20
char status sys code lena int log sel index
網上現有的全庫查詢,無法識別自定義架構的數據庫結構:
declare @str nvarchar(10) declare @tablename varchar(50) declare @colname varchar(50) declare @counts int declare @sql nvarchar(2000)--以上定義變量 declare cur1 cursor for select a.name tablename,B.name colname from sys.objects a,syscolumns b where a.object_id=b.id and a.type_desc=‘USER_TABLE‘--定義遊標 set @str=‘海‘ --設置要查找的字符 Open cur1 --打開遊標 Fetch next From cur1 Into @tablename,@colname While(@@Fetch_Status = 0) --循環 Begin set @sql=N‘select @counts=COUNT(*) from ‘ + @tablename + ‘ where charindex(‘‘‘+@str+‘‘‘,‘+@colname+‘)>0‘ exec sp_executesql @sql,N‘@counts int output‘,@counts output --執行動態sql if @counts>0 --判斷某個表某個字段是否存在特定字符 begin print @tablename+‘,‘+@colname --打印表名及字段名 end Fetch next From cur1 Into @tablename,@colname End Close cur1 --關閉遊標 Deallocate cur1 --釋放遊標
添加架構支持後,雖偶爾會有報錯,可查詢架構:
declare @str nvarchar(10) declare @schemasname varchar(50)declare @tablename varchar(50) declare @colname varchar(50) declare @counts int declare @sql nvarchar(2000)--以上定義變量 declare cur1 cursor for select s.name schemasname,a.name tablename,B.name colname from sys.objects a,syscolumns b,sys.schemas s where a.object_id=b.id and a.schema_id=s.schema_id and a.type_desc=‘USER_TABLE‘--定義遊標 set @str=‘汙染‘ --設置要查找的字符 Open cur1 --打開遊標 Fetch next From cur1 Into @schemasname,@tablename,@colname While(@@Fetch_Status = 0) --循環 Begin set @sql=N‘select @counts=COUNT(*) from ‘ + @schemasname + ‘.‘+ @tablename + ‘ where charindex(‘‘‘+@str+‘‘‘,‘+@colname+‘)>0‘ exec sp_executesql @sql,N‘@counts int output‘,@counts output --執行動態sql if @counts>0 --判斷某個表某個字段是否存在特定字符 begin print @schemasname+‘,‘+@tablename+‘,‘+@colname --打印表名及字段名 end Fetch next From cur1 Into @schemasname,@tablename,@colname End Close cur1 --關閉遊標 Deallocate cur1 --釋放遊標
sqlserver 全庫查詢 帶架構