Stored procedure parses correctly but will not execute. Invalid object name. Msg 208 - sql

I've scripted up a stored procedure as follows. It will parse without errors, but when I try to execute it, it will fail. The error message reads: Msg 208, Level 16, State 6, Procedure aspnet_updateUser, Line 23
Invalid object name 'dbo.aspnet_updateUser'.
Here is the stored procedure.
USE [PMRS2]
GO
/****** Object: StoredProcedure [dbo].[aspnet_updateUser] Script Date: 05/25/2009 15:29:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[aspnet_updateUser]
-- Add the parameters for the stored procedure here
#UserName nvarchar(50),
#Email nvarchar(50),
#FName nvarchar(50),
#LName nvarchar(50),
#ActiveFlag bit,
#GroupId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE dbo.aspnet_Users
SET UserName = #UserName, LoweredUserName = LOWER(#UserName), Email = #Email, FName = #FName, LName = #LName, ActiveFlag = #ActiveFlag, GroupId = #GroupId
WHERE LoweredUserName = LOWER(#UserName)
END

Looks like it might not exist yet, swap the Alter to a Create.

To avoid this happening in the furture, do what we do, never use alter proc. Instead we check for the existance of the proc and drop it if it exists, then create it with the new code:
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'myProc')
BEGIN
DROP Procedure myProc
END
GO
CREATE PROCEDURE myProc
(add the rest of the proc here)

Here is another solution
USE [PMRS2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID ( 'dbo.YourProcedureName', 'P' ) IS NOT NULL
DROP PROCEDURE dbo.YourProcedureName;
GO
CREATE PROCEDURE [dbo].[YourProcedureName] (
#UserName varchar(50),
#Password varchar(50))
AS
BEGIN
SET NOCOUNT ON;
select ... (your query)
END

Related

Stored Procedures & SQL Server

I'm doing some revision in SQL Server and I have a question that I'm trying to work out, I'm meant to be creating a stored procedure that displays all details of branch name, book code, and quantity on hand,the stored procedure takes parameter called #BranchName. I'm also meant to use EXEC to call this procedure with a value for the parameter.
This is my statement so far (I know that it's wrong and doesn't work some reason, I can't work it out)
CREATE PROCEDURE BranchDetails
SELECT
B.BookCode, BR.BranchName, I.OnHand
FROM
BOOK, BRANCH, INVENTORY
WHERE
BranchName = 'BookCode'
MSSQL Syntax
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
-- Add the parameters for the stored procedure here
<#Param1, sysname, #p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
<#Param2, sysname, #p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT <#Param1, sysname, #p1>, <#Param2, sysname, #p2>
END
GO
to solve your issue.
CREATE PROCEDURE BranchDetails #BranchCode varchar(20)
as
BEGIN
SELECT B.BookCode, BR.BranchName, I.OnHand
FROM BOOK, BRANCH, INVENTORY
WHERE BranchCode = #BranchCode
END
To execute
exec BranchDetails 'Disneyland'

Executing a statement within a stored procedure, out parameter always returns 0

I need to insert some values into a table and to do this I created a stored procedure. 4 values are passed. And two values can be inserted straight into the table, for two other values an ID needs to be found.
I have three stored procedures. When I execute the main stored procedure, I can see that the two called stored procedures are executed and come up with the correct value. However this value is not passed into the parameter.
Both parameters #uid and #did retrun 0 (zero) into the table.
What am I doing wrong??
Kind regards,
Clemens Linders
SP MES_D_GetUserID, Pass a name and you gat an ID as string
SP MES_D_GetDOrderID, Pass a name and you get an ID as integer
The main stored procedure:
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_Consumed]
#WERKS nvarchar(4), #USERNAME nvarchar(50), #MACHID int, #DRINKORDER nvarchar(50)
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
Declare #uid AS varchar(10)
Declare #did AS int
Declare #OUTUID AS varchar(10)
Declare #OUTDID AS int
exec #uid = MES_D_GetUserID #USERNAME, #OUTUID OUTPUT;
exec #did = MES_D_GetDOrderID #DRINKORDER, #OUTDID OUTPUT;
INSERT INTO Demo_D_Consumed (Werks, UserID, MachID, DrinkID, TimeDate) VALUES (#WERKS, #uid, #MACHID, #did, GETDATE());
END
and these are the two other stored procedures :
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_GetDOrderID]
#DRINK nvarchar(50), #OUTDID int OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT RecordNr FROM DEMO_D_ORDERS WHERE Drink = #DRINK
END
USE [AddOn_DEV_HE]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MES_D_GetUserID]
#USERNAME nvarchar(50), #OUTUID nvarchar(50) OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT UserLan FROM sysUsernames WHERE UserName = #USERNAME
END
Change them to be
ALTER PROCEDURE [dbo].[MES_D_GetDOrderID]
#DRINK nvarchar(50), #OUTDID int OUTPUT
WITH EXEC AS CALLER
AS
BEGIN
SET NOCOUNT ON;
SELECT #OUTDID = RecordNr FROM DEMO_D_ORDERS WHERE Drink = #DRINK
END
And
exec MES_D_GetDOrderID #DRINKORDER, #OUTDID OUTPUT;
Your #OUTDID will have the return value. Same with the other SP.

Trigger Failing when calling Stored Procedure

I am truly hoping someone can help me out...
I have a trigger to handle the insert of a new record to a table. This trigger, as you will see below, inserts a record into another table, which in turns executes a trigger on that table, that calls a stored procedure (I tried to do it within the trigger itself, but it failed and was difficult to test where it was failing, so I moved it into its own little unit.)
Within the stored procedure, there is a call to extract information from the Active Directory database (ADSI) and update the newly inserted record. However, this is where it fails when called by the trigger. When I call it by simply executing it, and passing along the record to be updated, it works great... Can anyone point me in the right direction? Please!!!
Trigger #1 in YYY
USE [YYY]
GO
/****** Object: Trigger [dbo].[NewCustodian] Script Date: 08/04/2014 09:38:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[NewCustodian]
ON [YYY].[dbo].[Custodians]
AFTER INSERT
AS BEGIN
SET NOCOUNT ON;
DECLARE #CaseID varchar(20);
DECLARE DBcursor CURSOR FOR
SELECT [XXX].[dbo].[tblCase].CaseID from [XXX].[dbo].[tblCase] Where [XXX].[dbo].[tblCase].SQLSVR_Case_ID = 'YYY';
Open DBcursor; FETCH DBCursor into #CaseID;
CLOSE DBcursor; DEALLOCATE DBcursor;
DECLARE #NAME varchar(255);
DECLARE #TAG varchar(255);
SELECT #NAME = name FROM inserted;
SELECT #TAG = tag FROM inserted;
IF NOT EXISTS (Select eID from [XXX].[dbo].[tblNames]
WHERE eID = #TAG and CaseID = #CaseID)
BEGIN
INSERT INTO [XXX].[dbo].[tblNames] (CaseID, Name, eID)
Values (#CaseID, #NAME, #Tag);
END
END
Trigger #2 in XXX
USE [XXX]
GO
/****** Object: Trigger [dbo].[tblNames_New] Script Date: 08/04/2014 08:56:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
ALTER TRIGGER [dbo].[tblNames_New]
ON [XXX].[dbo].[tblNames]
AFTER INSERT
AS BEGIN
SET NOCOUNT ON;
DECLARE #NamesID varchar(10)
DECLARE #TAG varchar(10);
DECLARE #return_value int
SELECT #NamesID = namesID FROM inserted
EXEC dbo.UpdateNames #NamesID;
End
Stored procedure:
USE [XXX]
GO
/****** Object: StoredProcedure [dbo].[UpdateNames] Script Date: 08/04/2014 08:14:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[UpdateNames]
#NamesID int
AS
BEGIN
SET FMTONLY OFF;
SET NOCOUNT ON;
DECLARE #eID varchar(10);
DECLARE #TAG varchar(10);
DECLARE #SQL nvarchar(555);
DECLARE #DBresults as table (
eID nvarchar(100),
mobile nvarchar(100),
mail nvarchar(100),
phone nvarchar(100),
name nvarchar(50),
legacyExchangeDN nvarchar(100),
Title nvarchar(100),
homeDirectory nvarchar(100));
DECLARE #mobile nvarchar(100)
DECLARE #mail nvarchar(100)
DECLARE #phone nvarchar(100) = 'Error'
DECLARE #name nvarchar(100)
DECLARE #legacyExchangeDN nvarchar(100)
DECLARE #Title nvarchar(100) = 'Error'
DECLARE #homeDirectory nvarchar(100)
SET #eID = (Select eID from [XXX].[dbo].[tblNames] Where NamesID = #NamesID)
SET #SQL = N'SELECT * FROM OpenQuery ( ADSI, ''SELECT homeDirectory,Title,legacyExchangeDN,displayName, telephoneNumber, mail, mobile,samAccountName
FROM ''''LDAP://domain.com''''
WHERE objectClass = ''''User'''' and samAccountName = ''''' + #eID+ ''''''') As tblADSI'
INSERT INTO #DBresults
EXEC sp_executesql #SQL
DECLARE DBcursor CURSOR FOR
SELECT * from #DBresults;
Open DBcursor; FETCH DBCursor into #eID, #mobile, #mail, #phone, #Name, #legacyExchangeDN, #Title, #homeDirectory;
CLOSE DBcursor; DEALLOCATE DBcursor;
UPDATE XXX.dbo.tblNames
SET Job_Title = #Title,
Phone = #Phone
Where NamesID = #NamesID;
END
As I said in my comment - a trigger should be extremely small, nimble, lean - do not do any extensive and time-consuming processing inside a trigger, and avoid anything that would cause performance bottlenecks, especially cursors!
The reason for this is the fact that a trigger will be triggered whenever an INSERT operation happens, you have no control over when and how many times it gets called. The main app will wait and hang while the trigger is at work - so therefore, don't make this a long time - return very quickly from your trigger to go on with your main app.
My approach would be:
create a new separate table where you insert some key pieces of information into from your first original trigger
CREATE TABLE NewCustodianInserted
(
ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
CaseID VARCHAR(20),
Tag VARCHAR(255),
Handled BIT DEFAULT (0)
);
change your original trigger on the Custodians table to just insert those key pieces of information into your new "command" table:
CREATE TRIGGER [dbo].[NewCustodian]
ON [YYY].[dbo].[Custodians]
AFTER INSERT
AS BEGIN
SET NOCOUNT ON;
-- insert key pieces about the new custodian into "command" table
INSERT INTO dbo.NewCustodianInserted (CaseID, Tag)
SELECT i.CaseId, i.Tag
FROM Inserted i
WHERE NOT EXISTS (SELECT * FROM [XXX].[dbo].[tblNames] WHERE eID = i.Tag AND CaseID = i.CaseID)
END
in a separate process, e.g. a SQL Server Agent job that is scheduled to run every 5 mînutes (or whatever makes sense for your application), read the "command" table, get the new custodians to handle, call that long-running stored procedure updating Active Directory from it. Here, since this runs asynchronously from your main application, it's ok to use a cursor which you almost have to since you want to call a stored procedure for every row in your new table.
CREATE PROCEDURE HandleNewCustodians
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CaseID VARCHAR(20);
DECLARE #Tag VARCHAR(255);
DECLARE #NamesID varchar(10);
DECLARE CustodianCursor CURSOR FAST_FORWARD
FOR
SELECT CaseID, Tag FROM dbo.NewCustodianInserted WHERE Handled = 0
OPEN CustodianCursor
FETCH NEXT FROM CustodianCursor INTO #CaseID, #Tag;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #NamesID = NameID
FROM [XXX].[dbo].[tblNames] WHERE eID = #Tag AND CaseID = #CaseID
EXEC dbo.UpdateNames #NamesID;
FETCH NEXT FROM CustodianCursor INTO #CaseID, #Tag;
END
CLOSE CustodianCursor;
DEALLOCATE CustodianCursor;
END

incorrect syntax near in creating stored procedure on a remote db

I am trying to recreate a stored procedure on a database which is hosted on a remote server.
When creating the same SP locally I don't get any errors but when I am trying to create the SP on the remote server I am getting this errors:
Msg 102, Level 15, State 1, Procedure MySP, Line 26
Incorrect syntax near 'MERGE'.
Msg 102, Level 15, State 1, Procedure MySP, Line 27
Incorrect syntax near 'S'.
Those errors are repeating in multiple SP and I didn't get them when I created the SP's on my local server.
Any idea what can that be?
Here is a sample SP:
USE [MyDatabase]
GO
/****** Object: StoredProcedure [dbo].[InsertContractorInfo] Script Date: 11/07/2012 01:08:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
--exec [dbo].[InsertContractorInfo]
CREATE PROCEDURE [dbo].[InsertContractorInfo]
(#CompanyName nvarchar(50),
#LicenseNumber nvarchar(50),
#MailingAddress1 nvarchar(200),
#MailingAddress2 nvarchar(200),
#Phone nvarchar(10),
#Fax nvarchar(10),
#Mobile nvarchar(10),
#Email nvarchar(200),
#PercentCommercial int,
#PercentResidental int,
#TotalEmployees int,
#AnnualSales decimal(18,2),
#InsuranceCompanyContact nvarchar(100)=null,
#InsuranceCompanyContactEmail nvarchar(100)=null,
#InsuranceCompanyContactPhone nvarchar(100)=null,
#ContractorID uniqueidentifier)
AS
BEGIN
MERGE dbo.Contractor con
USING(SELECT 1 S) S
ON con.Oid = #ContractorID
WHEN MATCHED THEN UPDATE
SET
[CompanyName] = #CompanyName
,[LicenseNumber] = #LicenseNumber
,[MailingAddress1] = #MailingAddress1
,[MailingAddress2] = #MailingAddress2
,[Phone] = #Phone
,[Fax] = #Fax
,[EMail] =#Email
,[Mobile] =#Mobile
,[PercentCommercial] = #PercentCommercial
,[PercentResidental] = #PercentResidental
,[TotalEmployees] = #TotalEmployees
,[ApproximateAnnualSales] = #AnnualSales
,[InsuranceCompanyContact] = #InsuranceCompanyContact
,[InsuranceCompanyContactPhone] = #InsuranceCompanyContactPhone
,[InsuranceCompanyContactEmail] = #InsuranceCompanyContactEmail
WHEN NOT MATCHED THEN
INSERT
([Oid]
,[CompanyName]
,[LicenseNumber]
,[MailingAddress1]
,[MailingAddress2]
,[Phone]
,[Fax]
,[EMail]
,[Mobile]
,[PercentCommercial]
,[PercentResidental]
,[TotalEmployees]
,[ApproximateAnnualSales]
,[InsuranceCompanyContact]
,[InsuranceCompanyContactPhone]
,[InsuranceCompanyContactEmail])
VALUES
(#ContractorId
,#CompanyName
,#LicenseNumber
,#MailingAddress1
,#MailingAddress2
,#Phone
,#Fax
,#EMail
,#Mobile
,#PercentCommercial
,#PercentResidental
,#TotalEmployees
,#AnnualSales
,#InsuranceCompanyContact
,#InsuranceCompanyContactPhone
,#InsuranceCompanyContactEmail
);
END
GO
Thanks, Laziale
This merger feature works with sql sever 2008 + versions , if you are trying to use in sql server 2005 you can do like this merge mimic in 2005
http://sqlserver-tips.blogspot.com/2006/09/mimicking-merge-statement-in-sql.html
You can try this also before CREATE PROCEDURE script.
USE [MyDatabase]
GO
IF EXISTS(SELECT Name FROM SysObjects WHERE ID = OBJECT_ID(N'[InsertContractorInfo]'))
BEGIN
DROP PROCEDURE InsertContractorInfo
END
GO

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.