Sql Server 2008 R2 查询一个实例中存在某个表的数据库(转载)

--exec  LsP_Sys_CheckTableExist 'dp_rule'
--Drop Proc LsP_Sys_CheckTableExist
Create Proc LsP_Sys_CheckTableExist
(
  @table Varchar(100)
)
/* 查询一个实例中存在某个表的数据库*/
As
--Declare @table Varchar(100)
--Select @table ='dp_rule'
--创建一个游标
  declare my_cursor cursor for     --my_cursor为游标的名称,随便起
  select name from Master..SysDatabases  order by Name     --这是游标my_cursor的值,这里随便发挥看业务场景
--打开游标
  open my_cursor                  --没什么好说的
--变量
  declare   @name varchar(50)     --这里是两个变量用来接收游标的值
--循环游标
  fetch next from my_cursor into @name  --获取my_cursor的下一条数据,其中为两个字段分别赋值给@id,@name
  while @@FETCH_STATUS=0 --假如检索到了数据继续执行
  begin
--print(@name) --print()打印变量 随便发挥
--select * from Master..SysDatabases where name=@name --这里是具体业务了,随便发挥。而我这是又执行了一次查询 
    exec('use ['+@name +'] '+ 'if Exists(SELECT Name FROM SysObjects Where XType=''U'' and name='''+@table+''') print '''+@name+'''  ')
    fetch next from my_cursor into @name --获取下一条数据并赋值给变量
  end--关闭释放游标

  close my_cursor
  deallocate my_cursor

-----------------------------

原文链接:https://www.cnblogs.com/Zuoyeye/p/13365016.html

猜你喜欢

转载自www.cnblogs.com/missddd/p/13365042.html
今日推荐