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

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.

Related

How to return an id and use it directly in another stored procedure?

I want his stored procedure to return the inserted id
ALTER PROCEDURE [dbo].[InsertAddress_DBO]
#Name VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Address]([Address_Name])
OUTPUT INSERTED.Address_Id
VALUES (#Name)
END
This one the same
ALTER PROCEDURE [dbo].[InsertDocumentation_DBO]
#Texte VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Documentation]([Documentation_Text])
OUTPUT inserted.Documentation_Id
VALUES (#Texte)
END
And this one to use them and return her own -
like using the inserted id to put it into the next stored procedure as a parameter
ALTER PROCEDURE [dbo].[InsertEstablishmentByStrings_DBO]
#Establishment_Name VARCHAR(50),
#Address_Name VARCHAR(50),
#Documentation_Text VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC #Address_ID = [dbo].[InsertAddress_DBO]
#Name = "rue de la banchiesserie 85 Golback"
EXEC #Documentation_ID = [dbo].[InsertDocumentation_DBO]
#Texte = "né en 55555 restaurant fabuleux"
INSERT INTO [dbo].[Establishment]([Establishment_Name],[Address_Id],[Documentation_Id])
OUTPUT inserted.Establishment_Id
VALUES (#Establishment_Name,#Address_ID,#Documentation_ID)
END
However, I always get an error, because the stored procedure doesn't return the id when I execute it.
What is wrong in my code?
I would like to get the code I could use again and again in each stored procedure I have to execute. I already tried ##Identity, indent, scoped,... nothing works.
If you want to return something from stored procedure to the context of SQL query execution you may use a return statement or an output parameter. I would suggest you to use the second option. The first one is generally intended to return status of procedure execution.
ALTER PROCEDURE [dbo].[InsertAddress_DBO]
#Name VARCHAR(50),
#Address_ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[Address]([Address_Name])
VALUES (#Name)
SET #Address_ID = SCOPE_IDENTITY()
END
Than you can use returned value in your outer procedure
ALTER PROCEDURE [dbo].[InsertEstablishmentByStrings_DBO]
#Establishment_Name VARCHAR(50),
#Address_Name VARCHAR(50),
#Documentation_Text VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC [dbo].[InsertAddress_DBO]
#Address_ID = #Address_ID OUTPUT,
#Name = "rue de la banchiesserie 85 Golback"
...
END
An OUTPUT INSERTED clause you used doesn't returns data to the query execution context but send them to the output stream.
Your stored procedures should look like this, using an OUTPUT parameter, not trying to consume a RETURN value (which should never contain data) using a resultset. Also [don't] [put] [everything] [in] [square] [brackets] [unless] [you] [have] [to], [because] [all] [it] [does] [is] [hamper] [readability], and don't surround string literals with "double quotes" because that means something else in T-SQL.
CREATE OR ALTER PROCEDURE dbo.InsertAddress_DBO
#Name varchar(50),
#Address_Id int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Address(Address_Name)
VALUES (#Name);
SELECT #Address_Id = SCOPE_IDENTITY();
END
GO
CREATE OR ALTER PROCEDURE dbo.InsertDocumentation_DBO
#Texte varchar(50),
#Doc_Id int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Documentation(Documentation_Text)
VALUES (#Texte);
SELECT #Doc_Id = SCOPE_IDENTITY();
END
GO
Now, your main procedure can do this:
CREATE OR ALTER PROCEDURE dbo.InsertEstablishmentByStrings_DBO
#Establishment_Name varchar(50),
#Address_Name varchar(50),
#Documentation_Text varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Address_ID INT ,
#Documentation_ID INT
EXEC dbo.InsertAddress_DBO
#Name = #Address_Name,
#Address_Id = #Address_ID OUTPUT;
EXEC dbo.InsertDocumentation_DBO
#Texte = Documentation_Text,
#Doc_Id = #Documentation_ID OUTPUT;
INSERT dbo.Establishment
(Establishment_Name, Address_Id, Documentation_Id)
OUTPUT inserted.Establishment_Id,
inserted.Address_ID, inserted.Documentation_ID
VALUES (#Establishment_Name,#Address_ID,#Documentation_ID);
END
GO
And you call it like this:
EXEC dbo.InsertEstablishmentByStrings_DBO
#Establishment_Name = 'Gaston''s',
#Address_Name = 'rue de la banchiesserie 85 Golback',
#Documentation_Text = 'né en 55555 restaurant fabuleux';
And get results like this:
Establishment_Id
Address_ID
Documentation_ID
1
1
1
Fully working example on db<>fiddle

String or binary data would be truncated error even though all parameters are within the limit

I have a stored procedure which i use to insert. I get this error when I try to insert by passing these values.
exec WorkDetail 'Insert',2,'2015-10-20','se31','entry','title','r','0','abh',
'client','proj','task','status','rea','module','2','4','stat','1'
This is the stored procedure.
USE [OMS]
GO
/****** Object: StoredProcedure [dbo].[WorkDetail] Script Date: 06/04/2016 09:52:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[WorkDetail]
#QueryType nvarchar(25),
#ReportNo numeric(18,0),
#ReportDate date,
#EmpCode nvarchar(15),
#Session nvarchar(50),
#ReportTitle nvarchar(50),
#ReportDesc nvarchar(Max),
#ReportType numeric(18,0),
#CreatedBy nvarchar(50),
#ClientPlace nvarchar(50),
#Project nvarchar(50),
#Task nvarchar(50),
#TaskStatus nvarchar(50),
#Reason nvarchar(250),
#Module nvarchar(50),
#EntryFrom nvarchar(50),
#EntryTo nvarchar(50),
#Status nvarchar(25),
#SQLReturn nvarchar(MAX) output
AS
BEGIN
SET NOCOUNT ON;
Begin Transaction WorkDetails
Declare #rcount int
set #rcount=0
if #QueryType='Insert'
Begin
if not exists(select * from WorkDetails where EmpCode=#EmpCode and ReportDate=#ReportDate and Session=#Session)
Begin
SET #ReportNo=(select ISNULL(MAX(ReportNo),0)+1 from WorkDetails)
Insert Into WorkDetails (ReportNo,ReportDate,EmpCode,Session,ReportTitle,ReportDesc,ReportType,Location,Project,Module,Task,TaskStatus,Reason,EntryFrom,EntryTo,Status,ReportTime,CreatedBy,CreatedDate,UpdatedBy,UpdateDate)
Values(#ReportNo,#ReportDate,#EmpCode,#Session,#ReportTitle,#ReportDesc,#ReportType,#ClientPlace,#project,#Module,#Task,#TaskStatus,#Reason,#EntryFrom,#EntryTo,#Status,GETDATE(),#CreatedBy,GETDATE(),#CreatedBy,GETDATE())
if ##ROWCOUNT>0
set #rcount=1
End
else
set #rcount=-1
End
if #rcount>0
Begin
commit transaction WorkDetails
set #SQLReturn='Success'
End
else if #rcount=-1
Begin
commit transaction WorkDetails
set #SQLReturn='Already'
End
Else
Begin
rollback transaction WorkDetails
set #SQLReturn='Failure'
End
END
This is the error:
Msg 8152, Level 16, State 13, Procedure WorkDetail, Line 33
String or binary data would be truncated.
The statement has been terminated.
I'm new to sql and just came across stored procedure.I saw other questions with this error but I don't understand which field extends the specified limit

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

Store the result of a stored procedure without using an output parameter

I have 2 stored procedures: up_proc1 and up_proc2.
This is (a simplified version of) up_proc2:
CREATE PROCEDURE dbo.up_proc2
#id_campaign uniqueidentifier, #id_subcampaign uniqueidentifier,
#id_lead uniqueidentifier, #offer NVARCHAR(1000) = NULL
AS
SET NOCOUNT ON
DECLARE #id UNIQUEIDENTIFIER
SELECT #id = id FROM prospects WHERE id_lead = #id_lead
AND id_campaign = #id_campaign AND id_subcampaign = #id_subcampaign
IF #id IS NULL
BEGIN
SET #id = newid ()
INSERT INTO prospects (id, id_campaign, id_subcampaign, id_lead, offer)
values (#id, #id_campaign, #id_subcampaign, #id_lead, #offer)
END
ELSE
BEGIN
UPDATE prospects set offer = #offer WHERE id=#id
END
SELECT #id AS ID
GO
From up_proc1 I call up_proc2. What I would like to achieve is to store the #id of up_proc2 in a variable declared in up_proc1. Is this possible without using an output parameter?
This is how up_proc1 looks like:
CREATE PROCEDURE dbo.up_proc1
AS
SET NOCOUNT ON
DECLARE #fromProc2 UNIQUEIDENTIFIER
-- NOT WORKING
-- select #fromProc2 = exec up_insertProspects [snip]
-- ALSO NOT WORKING
-- exec #fromProc2 = up_insertProspects [snip]
What you could do is store the output into a table variable:
DECLARE #tmpTable TABLE (ID UNIQUEIDENTIFIER)
INSERT INTO #tmpTable
EXEC dbo.up_proc2 ..........
and then go from there and use that table variable later on.
You can certainly consume this as an output parameter in proc2 without affecting how your C# code retrieves the eventual resultset.
ALTER PROCEDURE dbo.up_proc2
#id_campaign uniqueidentifier,
#id_subcampaign uniqueidentifier,
#id_lead uniqueidentifier,
#offer NVARCHAR(1000) = NULL,
#fromProc2 UNIQUEIDENTIFER = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
...
C# can ignore the new parameter since it is nullable (but since a single output parameter is more efficient than a data reader, you may consider updating your C# code to take advantage of the output parameter later).
Now in proc1:
ALTER PROCEDURE dbo.up_proc1
AS
BEGIN
SET NOCOUNT ON;
DECLARE #fromProc2 UNIQUEIDENTIFIER;
EXEC dbo.up_proc2
--... other parameters ...,
#fromProc2 = #fromProc2 OUTPUT;
-- now you can use #fromProc2
END
GO

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

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