0
SQL 쿼리를 실행하여 여러 데이터베이스에 저장 프로 시저를 만들려고합니다.많은 데이터베이스에 대해 저장 프로 시저를 만드는 쿼리가 예기치 않게 실패합니다.
나는 다음과 같은 쿼리를 실행하고 그러나
DECLARE @sqlStmt nvarchar(max)
select name from sys.databases where name not in ('master', 'tempdb', 'model', 'msdb')
DECLARE dbCursor CURSOR
FOR select name from sys.databases where name not in ('master', 'tempdb', 'model', 'msdb')
DECLARE @dbname varchar(max)
OPEN dbCursor
fetch next from dbCursor into @dbname
while @@FETCH_STATUS = 0
BEGIN
declare @stmt nvarchar(max)
SET @stmt = 'USE ' + @dbname + ';';
EXECUTE sp_executesql @stmt
declare @correctTableExists bit
set @correctTableExists = (select case when Exists(SELECT TABLE_SCHEMA + '.' + TABLE_NAME, *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME in ('MasterSchedules', 'Client'))
THEN 1
ELSE 0
END)
if @correctTableExists = 1
BEGIN TRY
set @stmt = 'USE ' + @dbName + '
GO
CREATE PROCEDURE spGetMasterScheduleByID
@masterScheduleID int
AS
BEGIN
SELECT * FROM MasterSchedules
WHERE MasterScheduleID = @masterScheduleID
END'
EXECUTE sp_executesql @stmt
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
print @stmt + '
Failed for ' + @dbName
END CATCH
FETCH NEXT FROM dbCursor
INTO @dbname
END
CLOSE dbCursor;
DEALLOCATE dbCursor;
을, 나는 다음과 같은 오류 메시지가 얻을 : 나는 메시지를 볼 때
Error 102
Incorrect syntax near 'GO'.
, 나는 모든 데이터베이스 이름에 대해 다음과 같은 메시지 참조 나는 이것에 대하여 달리고있다 :
(1 row(s) affected)
USE [Database Name]
GO
CREATE PROCEDURE spGetMasterScheduleByID
@masterScheduleID int
AS
BEGIN
SELECT * FROM MasterSchedules
WHERE MasterScheduleID = @masterScheduleID
END
Failed for [Database Name]
왜 이것이 "틀린다고 생각 하는가? 신택스 "는 분명히 완벽하게 유효한 신택스인가? 해당 정확한 쿼리를 복사하여 SSMS에 붙여 넣으면 쿼리가 완벽하게 작동합니다.
나는 이미exec @stmt
execute @stmt
execute (@stmt)
EXECUTE sp_executesql @stmt