所以我正在尝试在不同的数据库中创建程序.我不应该知道数据库的名称.我试图制作嵌套游标,第一个用动态方式获取数据库名称,另一个用于创建/改变过程; 我使用EXISTS创建过程而不是EXEST来改变它们.但不知何故,数据库仍然存在于'master'中,而且它永远不会覆盖其他数据库.我知道我的内嵌式光标存在问题,但我不知道这是什么.这是我的编码:
DECLARE GetDatabases CURSOR FOR SELECT name FROM sys.databases OPEN GetDatabases DECLARE @DBName NVARCHAR(100) DECLARE @cmd NVARCHAR(Max) FETCH NEXT FROM GetDatabases INTO @DBName WHILE @@FETCH_STATUS = 0 BEGIN set @cmd='use ' + @DBName print @cmd exec sp_executesql @cmd FETCH NEXT FROM GetDatabases INTO @DBName DECLARE AutoProc CURSOR FOR SELECT TABLE_SCHEMA,TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' OPEN AutoProc DECLARE @TableName NVARCHAR(100) DECLARE @TableSchema NVARCHAR(100) FETCH NEXT FROM AutoProc INTO @TableSchema,@TableName WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS(SELECT * FROM sys.objects WHERE type = 'P' AND OBJECT_ID = OBJECT_ID('@TableName')) exec('ALTER PROCEDURE USP_SELECT_'+@TableName+' AS BEGIN SELECT * FROM '+@TableSchema+'.'+@TableName+' END ;') IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND OBJECT_ID = OBJECT_ID('@TableName')) exec('CREATE PROCEDURE USP_SELECT_'+@TableName+' AS BEGIN SELECT * FROM '+@TableSchema+'.'+@TableName+' END ;') FETCH NEXT FROM AutoProc INTO @TableSchema,@TableName END CLOSE AutoProc DEALLOCATE AutoProc END CLOSE GetDatabases DEALLOCATE GetDatabases
PS:我不应该知道数据库的名称,因为我正在尝试编写"常规"程序,因此它可以应用于所有sql-server用户的数据库,而不仅仅是我的数据库.
P.S2:我使用了Nesting Cursors,但是由于它们的灾难性表现,我也很欣赏其他方式!
干杯!