帮我看看如何实现这个需求

Airroll 2008-08-22 09:56:21
求助一个存储过程的写法


我有个需求
就是首先要
遍历所有实例拥有的database
执行select count(1) from sysobjects where xtype='U'
如果返回值大于0就把dbname显示出来


简单说就是判断当前实例是否存在空库


以下是我写的procedure

create procedure IF_NULL_DATABASE
as
declare @db_name varchar(20)
declare @sql_body varchar(200)
declare @cnt int
set @cnt=0
declare cur_name cursor for select name from sys.sysdatabases for read only
open cur_name ;
fetch next from cur_name into @db_name ;
while @@FETCH_STATUS = 0
begin
exec('use ' + @db_name) exec ('select count(1) from sysobjects where xtype ='U'')
print @db_name
print @cnt
Fetch From cur_name into @db_name;
if @cnt = 0
begin
insert into tmp_db_name(name) values (@db_name)
end
end
close cur_name
deallocate cur_name

但是抛出
Msg 102, Level 15, State 1, Procedure IF_NULL_DATABASE, Line 13
Incorrect syntax near 'U'.

大家给点意见吧
...全文
83 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Airroll 2008-08-22
  • 打赏
  • 举报
回复
谢谢
我已解决~
netcup 2008-08-22
  • 打赏
  • 举报
回复
有个存储过程好像可以遍历数据库,好像是sp_geteachdb,还有个遍历数据库中的所有表的过程,和这个有点像。这个在联机帮助中没有。记不太清了,你可以试下或者BAIDU下。
cqq 2008-08-22
  • 打赏
  • 举报
回复
这个只能在 master库执行吧, 也就是说只能 use master吧
Airroll 2008-08-22
  • 打赏
  • 举报
回复
这个转义字符的问题我晓得了

谢谢


但是select @cnt=count(1) from sysobjects where xtype ='U'的结果每次都一样,我想是因为前面use ***这条的缘故
大家给点意见吧
cqq 2008-08-22
  • 打赏
  • 举报
回复
exec ('select count(1) from sysobjects where xtype ='U'')
一个单引号用两个单引号替换

exec ('select count(1) from sysobjects where xtype =''U''')

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧