Table-valued parameter error in SQL Server - sql

I'm working on a reporting module for a company project. Although we use an ORM for our application, I've decided to write stored procedures for the reports in anticipation of migrating to SSRS.
These stored procedures require table-valued parameter input. As such, I've created my table type:
USE MyDatabase
GO
/****** Object: UserDefinedTableType [dbo].[IntList] Script Date: 5/8/2013 5:20:59 PM ******/
CREATE TYPE [dbo].[IntList] AS TABLE(
[Id] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO
I have the following SQL Server stored proc:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
USE MyDatabase
GO
-- =============================================
-- Author: <lunchmeat317>
-- Create date: <05/06/2013>
-- Description: <File Type Report>
-- =============================================
ALTER PROCEDURE Report_FileType
#filetype varchar(20) = null,
#User intList READONLY,
#Group intList READONLY
AS
BEGIN
SET NOCOUNT ON;
/*
lf = LibraryFile
lfu = LibraryFileAssignedUser
lfg = LibraryFileAssignedGroup
*/
SELECT Extension AS FileType, COUNT(1) AS TotalFiles
FROM LibraryFile lf
LEFT JOIN LibraryFileAssignedUser lfu
ON (SELECT COUNT(1) FROM #User) != 0
AND lfu.LibraryFileId = lf.Id
LEFT JOIN LibraryFileAssignedGroup lfg
ON (SELECT COUNT(1) FROM #Group) != 0
AND lfg.LibraryFileId = lf.Id
WHERE ((#filetype IS NULL) OR (Extension = #filetype))
AND (
((#User IS NULL) OR (lfu.UserId IN (SELECT * FROM #User)))
OR ((#Group IS NULL) OR (lfg.HubGroupId IN (SELECT * FROM #Group)))
)
GROUP BY Extension
END
GO
When I attempt to alter the stored procedure, I continually get the error message
Msg 137, Level 16, State 1, Procedure Report_FileType
Must declare the scalar variable "#User".
Msg 137, Level 16, State 1, Procedure Report_FileType
Must declare the scalar variable "#Group".
I can't figure out why this is happening. If I do use a scalar type (and update my code to match) it works. However, when I try to use a TVP, I can't compile the stored procedure.
For what it's worth, I've added the type, but I haven't set the permission on it yet. However, I don't expect that would cause a compilation error; it would only cause an error at runtime (which I've dealt with before).
Does anyone have any experience with this issue? Thanks!

Interesting, I haven't used this before, but it seems that you cannot test for #User / #Group IS NULL since it is a table.
Cf.
https://dba.stackexchange.com/questions/30754/how-do-i-check-for-a-null-or-empty-table-valued-parameter
http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/c59f6b82-7639-42c7-ad90-a4ec7315a3bd/

Related

Operand type clash when compiling a native stored procedure in SQL Server 2019

Any idea why I can compile this stored procedure with the first Insert but not the second (or both)? The error message is:
Msg 206, Level 16, State 2, Procedure InsertExtPageWithXML, Line 21 [Batch Start Line 11]
Operand type clash: numeric is incompatible with uniqueidentifier
THis is the SQL code:
--======================================================
-- Create Natively Compiled Stored Procedure Template
--======================================================
USE [PortalMO]
GO
-- Drop stored procedure if it already exists
IF OBJECT_ID('InsertExtPageWithXML','P') IS NOT NULL
DROP PROCEDURE [dbo].[InsertExtPageWithXML]
GO
CREATE PROCEDURE [dbo].[InsertExtPageWithXML]
-- Add the parameters for the stored procedure here
-- (not inserted is the auto-generated UI [PK_Id], non-null, primary key..)
(#1_Topic_PK uniqueidentifier = NULL,
#1_Path nvarchar(500) = "fix.me",
#1_Title nvarchar(450) = "fix.me",
#1_URL nvarchar(max) = "fix.me",
#1_Priority tinyint = NULL,
#1_Type nvarchar(50) = NULL,
#2_XMLfragment nvarchar(max) = "fix.me")
-- (all of the types above are accurate to the schemas already in existence)
WITH NATIVE_COMPILATION, SCHEMABINDING
AS BEGIN ATOMIC WITH
(
TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'us_english'
)
--Insert statements for the stored procedure here
INSERT INTO [dbo].[ExternalPage] (Topic_PK, Path, Title, URL, Priority, Type, LastUpdated)
VALUES (#1_Topic_PK, #1_Path, #1_Title, #1_URL, #1_Priority, #1_Type, GETDATE());
INSERT INTO [dbo].[XML] (Associated_PK, Type, XMLfragment, LastUpdated)
VALUES (SCOPE_IDENTITY(), N'ExternalPage', #2_XMLfragment, GETDATE());
END
GO

unqiueidenfitier is not compatible with type int SQL Server Procedure

I have the following procedure for inserting into a user table:
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andy Armstrong
-- Create date:
-- Description:
-- =============================================
CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15)
AS
BEGIN
DECLARE #GUID UNIQUEIDENTIFIER
SET #GUID = NEWID();
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO tblMemberLogin
(
UserID,
LoginName,
LoginPassword
)
VALUES
(
#GUID,
#LoginName,
#LoginPassword
)
RETURN #GUID
END
GO
However when I execute it I get the following error:
Msg 206, Level 16, State 2, Procedure db_SignupAddLogin, Line 34
Operand type clash: uniqueidentifier is incompatible with int
I cannot quite workout why as i am not referencing an int anywhere.
My Schema for tblMemberLogin looks like this:
UserID(PK,uniqueidentifier,notnull)
LoginName(nchar(15),not null)
LoginPassword(nchar(15),not null)
Please help!
RETURN can only be used with an int. You can simply use a SELECT query to retrieve the value of variable #GUID.
Reference: http://technet.microsoft.com/en-us/library/ms174998(v=sql.110).aspx
get rid of RETURN #GUID and you should be good to go.
In SQL Server, stored procedures may only return integer values. SQL Server RETURN
If you want to return data from a stored procedure other than an integer, you can use an output parameter: Returning Data from Stored Procedures
You declare the output parameter along with your input parameters:
CREATE PROCEDURE CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15),
#NewGuid UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #NewGuid = NEWID();
-- rest of procedure
END
And then use the output parameter:
DECLARE #NewLoginGuidFromSP UNIQUEIDENTIFIER
EXECUTE db_SignupAddLogin 'Username', 'password', #NewGuid = #NewLoginGuidFromSP OUTPUT;

Unable to call stored procedure within stored procedure

I have three stored procedures A, B, C
and definition of A is like
StoredProcedure A
As
Begin
--Some Stuff
Exec DBO.B [Derived Conitions]
Exec DBO.C [Derived Conitions]
END
but whenever I tried to execute the stored procedure A, at parsing time it give waring;
The module 'A' depends on the missing object 'B'. The module will still be created;
however, it cannot run successfully until the object exists.
The module 'A' depends on the missing object 'C'. The module will still be created;
however, it cannot run successfully until the object exists.
At execution time it throws exception
Could not find stored procedure 'dbo.B'.
Could not find stored procedure 'dbo.C'.
I found so many answers for calling a stored procedure with in stored procedure, but none of them worked for me.
You certainly can execute multiple procedures from within a single SP. You can even us the results from 1 SP as parameters in another.
In your specific case I suspect that there is a permissions / security or collation error which is stopping you from access the B and C stored procs.
Here is an example of SP chaining at work.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[DerivedProcedures]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Temporary table used to store results from SP1
DECLARE #Results_ForStoredProcedure1 TABLE
(
[SPID] INT,
[Status] NVARCHAR(50),
[Login] NVARCHAR(50),
[HostName] NVARCHAR(50),
[BlkBy] NVARCHAR(5),
[DBName] NVARCHAR(50),
[Commad] NVARCHAR(50),
[CPUTime] INT,
[DiskIO] INT,
[LastBatch] NVARCHAR(50),
[ProgramName] NVARCHAR(50),
[SPID2] INT,
[RequestId] INT
)
-- Execute SP1
INSERT INTO #Results_ForStoredProcedure1
EXEC sp_who2
-- Temporary table to store the results from SP2
DECLARE #Results_ForStoredProcedure2 TABLE
(
[DatabaseName] NVARCHAR(50),
[DatabaseSize] INT,
[Remarks] NVARCHAR(50)
)
-- Execute SP2
INSERT INTO #Results_ForStoredProcedure2
EXEC sp_databases
-- do something with both SP results
SELECT DISTINCT SP2.*
FROM #Results_ForStoredProcedure1 AS SP1
INNER JOIN #Results_ForStoredProcedure2 AS SP2 ON SP2.DatabaseName = SP1.DBName
WHERE SP1.DBName IS NOT NULL
END
GO
-- TEST
EXECUTE [dbo].[DerivedProcedures]
Perhaps, it sounds hilarious but I was getting the mentioned issue as I was using the wrong DB name (for example-Use 'XYZ'). Actually, in my case I was transferring a SP from one environment to another but after doing so I would not change the corresponding DB name .Due to which I was getting the error as the SPs which were involved were present in different DBs in the dissimilar environment.
In nutshell,please check the DB name which should be the very first line of your SP.
For example- Use 'XYZ'.

How to add code to initialize sql database

I use codefirst and I use Elmah.
I recreated every time the database, you must manually add the code from the file:
/*
ELMAH - Error Logging Modules and Handlers for ASP.NET
Copyright (c) 2004-9 Atif Aziz. All rights reserved.
Author(s):
Atif Aziz, http://www.raboof.com
Phil Haacked, http://haacked.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
-- ELMAH DDL script for Microsoft SQL Server 2000 or later.
-- $Id: SQLServer.sql 677 2009-09-29 18:02:39Z azizatif $
DECLARE #DBCompatibilityLevel INT
DECLARE #DBCompatibilityLevelMajor INT
DECLARE #DBCompatibilityLevelMinor INT
SELECT
#DBCompatibilityLevel = cmptlevel
FROM
master.dbo.sysdatabases
WHERE
name = DB_NAME()
IF #DBCompatibilityLevel <> 80
BEGIN
SELECT #DBCompatibilityLevelMajor = #DBCompatibilityLevel / 10,
#DBCompatibilityLevelMinor = #DBCompatibilityLevel % 10
PRINT N'
===========================================================================
WARNING!
---------------------------------------------------------------------------
This script is designed for Microsoft SQL Server 2000 (8.0) but your
database is set up for compatibility with version '
+ CAST(#DBCompatibilityLevelMajor AS NVARCHAR(80))
+ N'.'
+ CAST(#DBCompatibilityLevelMinor AS NVARCHAR(80))
+ N'. Although
the script should work with later versions of Microsoft SQL Server,
you can ensure compatibility by executing the following statement:
ALTER DATABASE ['
+ DB_NAME()
+ N']
SET COMPATIBILITY_LEVEL = 80
If you are hosting ELMAH in the same database as your application
database and do not wish to change the compatibility option then you
should create a separate database to host ELMAH where you can set the
compatibility level more freely.
If you continue with the current setup, please report any compatibility
issues you encounter over at:
http://code.google.com/p/elmah/issues/list
===========================================================================
'
END
GO
/* ------------------------------------------------------------------------
TABLES
------------------------------------------------------------------------ */
CREATE TABLE [dbo].[ELMAH_Error]
(
[ErrorId] UNIQUEIDENTIFIER NOT NULL,
[Application] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Host] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Type] NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Source] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Message] NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[User] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[StatusCode] INT NOT NULL,
[TimeUtc] DATETIME NOT NULL,
[Sequence] INT IDENTITY (1, 1) NOT NULL,
[AllXml] NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD
CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ELMAH_Error] ADD
CONSTRAINT [DF_ELMAH_Error_ErrorId] DEFAULT (NEWID()) FOR [ErrorId]
GO
CREATE NONCLUSTERED INDEX [IX_ELMAH_Error_App_Time_Seq] ON [dbo].[ELMAH_Error]
(
[Application] ASC,
[TimeUtc] DESC,
[Sequence] DESC
)
ON [PRIMARY]
GO
/* ------------------------------------------------------------------------
STORED PROCEDURES
------------------------------------------------------------------------ */
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml]
(
#Application NVARCHAR(60),
#ErrorId UNIQUEIDENTIFIER
)
AS
SET NOCOUNT ON
SELECT
[AllXml]
FROM
[ELMAH_Error]
WHERE
[ErrorId] = #ErrorId
AND
[Application] = #Application
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[ELMAH_GetErrorsXml]
(
#Application NVARCHAR(60),
#PageIndex INT = 0,
#PageSize INT = 15,
#TotalCount INT OUTPUT
)
AS
SET NOCOUNT ON
DECLARE #FirstTimeUTC DATETIME
DECLARE #FirstSequence INT
DECLARE #StartRow INT
DECLARE #StartRowIndex INT
SELECT
#TotalCount = COUNT(1)
FROM
[ELMAH_Error]
WHERE
[Application] = #Application
-- Get the ID of the first error for the requested page
SET #StartRowIndex = #PageIndex * #PageSize + 1
IF #StartRowIndex <= #TotalCount
BEGIN
SET ROWCOUNT #StartRowIndex
SELECT
#FirstTimeUTC = [TimeUtc],
#FirstSequence = [Sequence]
FROM
[ELMAH_Error]
WHERE
[Application] = #Application
ORDER BY
[TimeUtc] DESC,
[Sequence] DESC
END
ELSE
BEGIN
SET #PageSize = 0
END
-- Now set the row count to the requested page size and get
-- all records below it for the pertaining application.
SET ROWCOUNT #PageSize
SELECT
errorId = [ErrorId],
application = [Application],
host = [Host],
type = [Type],
source = [Source],
message = [Message],
[user] = [User],
statusCode = [StatusCode],
time = CONVERT(VARCHAR(50), [TimeUtc], 126) + 'Z'
FROM
[ELMAH_Error] error
WHERE
[Application] = #Application
AND
[TimeUtc] <= #FirstTimeUTC
AND
[Sequence] <= #FirstSequence
ORDER BY
[TimeUtc] DESC,
[Sequence] DESC
FOR
XML AUTO
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[ELMAH_LogError]
(
#ErrorId UNIQUEIDENTIFIER,
#Application NVARCHAR(60),
#Host NVARCHAR(30),
#Type NVARCHAR(100),
#Source NVARCHAR(60),
#Message NVARCHAR(500),
#User NVARCHAR(50),
#AllXml NTEXT,
#StatusCode INT,
#TimeUtc DATETIME
)
AS
SET NOCOUNT ON
INSERT
INTO
[ELMAH_Error]
(
[ErrorId],
[Application],
[Host],
[Type],
[Source],
[Message],
[User],
[AllXml],
[StatusCode],
[TimeUtc]
)
VALUES
(
#ErrorId,
#Application,
#Host,
#Type,
#Source,
#Message,
#User,
#AllXml,
#StatusCode,
#TimeUtc
)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I execute this code automatically?
I tried to use db.Database.ExecuteSqlCommand but I get lots of errors of the form:
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'ALTER'.
Incorrect syntax near the keyword 'ALTER'.
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'SET'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "#ErrorId".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "#TotalCount".
Must declare the scalar variable "#PageIndex".
Must declare the scalar variable "#TotalCount".
Must declare the scalar variable "#Application".
Must declare the scalar variable "#PageSize".
Must declare the scalar variable "#PageSize".
Must declare the scalar variable "#Application".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "#ErrorId".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Try this migration, bearing in mind that it expects all GO statements to be on a single line and that the file uses \r\n line endings. I installed Elmah using the elmah.sqlserver NuGet package, which drops the SqlServer.sql file in the appropriate location. You will need to change the resource name to match your project.
public partial class Elmah : DbMigration
{
public override void Up()
{
var sqlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProject.App_Readme.Elmah.SqlServer.sql");
using(var sqlStreamReader = new StreamReader(sqlStream))
{
string sqlScript = sqlStreamReader.ReadToEnd();
ExecuteSqlScript(sqlScript);
}
}
void ExecuteSqlScript(string sqlScript)
{
string[] sql = sqlScript.Split(new[] {"\r\nGO\r\n"}, StringSplitOptions.RemoveEmptyEntries);
foreach (var sqlCommand in sql)
{
if (!string.IsNullOrWhiteSpace(sqlCommand))
Sql(sqlCommand);
}
}
public override void Down()
{
DropTable("ELMAH_Error");
Sql("DROP PROCEDURE ELMAH_GetErrorXml");
Sql("DROP PROCEDURE ELMAH_GetErrorsXml");
Sql("DROP PROCEDURE ELMAH_LogError");
}
}
I
just to formalize my comment to the OP as an answer;
I think that the best practice here would be that only your code-first db should be affected by any radical changes (i.e. recreation of the db on the model changing). All other tables unrelated to that should be in an ApplicationServices db or similar and NOT in the core db. That way you don't create a support nightmare everytime you need to update your model with a simple property or data type change. Plus, you do of course end up losing the entire history of your logging (and other) db tables every time you make a change.
So, in a word, I think you're tackling the wrong problem with a potentially inappropriate solution.
This is certainly how we do it in our shop and in previous projects that I've worked on.
This is a series of SQL commands separated by GO statements (which aren't strictly T-SQL commands)
You can use SQL Managment Studio to execute the script, or the command line tool SQLCMD.exe
I don't think you should run that many batches on ExecuteSqlCommand.
Why don't you simply execute it on SSMS?
You'll need to parse your script, split it to separate SQL commands and execute each one of them individually through SqlCommand. Unfortunately, I'm not aware of a way to automate this.
The script requires you to separate the batches (GO is the batch separator) and send each batch individually to SQL Server. I actually have a sample project dbutilsqlcmd that does just that, and also supports more of the sqlcmd extensions like :setvar and $(variable) replacement in the script, which can be quite useful at deployment.
There is now a nuget package that will initialize the Elmah table and procs for you: https://www.nuget.org/packages/Elmah.SqlServer.EFInitializer/. Add it to your web project. It will then use EF code first to create it for you. It adds an Initializer to your App_Start folder so you actually don't have to add any code. It will add a migration to your database to ensure it only gets added once.

Invalid Object Name - Stored Procedure

I am creating a stored procedure in SQL Server via SSMS.
I have written the stored procedure below, however when I click execute it am given the error:
Msg 208, Level 16, State 6, Procedure NewQuestion, Line 11
Invalid object name 'hgomez.NewQuestion'.
the table is ownership is correct. (hgomez.Questions)
USE [devworks_oscar]
GO
/****** Object: StoredProcedure [hgomez].[NewQuestion] Script Date: 10/23/2011 23:55:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
Thanks in advance
I was a fan of always prepending my CREATE statements with an explicit check for existence and dropping if it was found.
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
That can be a bit of hassle with regard to permissions so others use an approach wherein they create a stub method only to immediately ALTER it.
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
This script tries to modify a procedure that already exists; it doesn't create the procedure.
To create the procedure use CREATE PROCEDURE
CREATE PROCEDURE [hgomez].[NewQuestion]
Once the procedure exists, you can modify its definition by using ALTER PROCEDURE
ALTER PROCEDURE [hgomez].[NewQuestion]
This solution https://stackoverflow.com/a/26775310/2211788 explained
If you drop and re-create a stored procedure it gets a new objectid - the list of stored procedures in SSMS is linked to the id it knows at the time the list was built. If you re-create it but don't refresh the stored procedures folder then any attempts to edit it will indicate the procedure is not found as the id has changed.
This happened to me once when I had two instances of SSMS open and I was working on the one I opened first. Closed them both down, reopened and it worked fine.