SSMS
 sql >> Database >  >> Database Tools >> SSMS

Nome oggetto non valido - stored procedure

Ero un fan di anteporre sempre il mio CREATE dichiarazioni con un esplicito controllo dell'esistenza e la caduta se è stata trovata.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'NewQuestion' AND ROUTINE_SCHEMA = 'hgomez')
BEGIN
    DROP PROCEDURE hgomez.NewQuestion
END
GO

-- this is always a CREATE
CREATE PROCEDURE [hgomez].[NewQuestion]
    (
    @QUESTIONNAME nvarchar(50),
    @QUESTION_ID int OUTPUT
    )

AS
    /* SET NOCOUNT ON */
    INSERT INTO [Questions] (QuestionText) VALUES (@QUESTIONNAME)
    SET @QUESTION_ID = SCOPE_IDENTITY();
    RETURN

Può essere un po' una seccatura per quanto riguarda le autorizzazioni, quindi altri usano un approccio in cui creano un metodo stub solo per ALTER immediatamente esso.

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'NewQuestion' AND ROUTINE_SCHEMA = 'hgomez')
BEGIN
    EXEC ('CREATE PROCEDURE hgomez.NewQuestion AS SELECT ''stub version, to be replaced''')
END
GO

-- This is always ALTER
ALTER PROCEDURE [hgomez].[NewQuestion]
    (
    @QUESTIONNAME nvarchar(50),
    @QUESTION_ID int OUTPUT
    )

AS
    /* SET NOCOUNT ON */
    INSERT INTO [Questions] (QuestionText) VALUES (@QUESTIONNAME)
    SET @QUESTION_ID = SCOPE_IDENTITY();
    RETURN