Getting rows affected in stored procedure INSERT statement with NOCOUNT OFF - sql-server

I have a stored procedure in SQL Server 2014 where I first delete data from a table and execute another stored procedure as shown below. I don't care about rows affected on this code so I use SET NOCOUNT ON. I then perform an Insert statement first setting SET NOCOUNT OFF. I would expect the stored procedure to return the rows affected automatically from the INSERT but that has not proven to be the case. I searched SO and found the ##ROWCOUNT and that is working. However, is that really required? Why wouldn't the INSERT statement in the code below return the records affected?
ALTER PROCEDURE [dbo].[SaveTextSetting]
#UserId INT ,
#SettingType INT = 0 ,
#SettingValue NVARCHAR(MAX)
AS
BEGIN
BEGIN
SET NOCOUNT ON;
DELETE FROM Settings
WHERE UserId = #UserId
AND SettingType = #SettingType;
EXEC dbo.PurgeExpiredSettings;
END;
BEGIN
SET NOCOUNT OFF;
INSERT INTO dbo.Settings
( UserId ,
SettingsText ,
SettingType
)
VALUES ( #UserId ,
#SettingValue ,
#SettingType
);
RETURN ##ROWCOUNT; --without this we don't get the rows affected
END;
END;

Are you sure?
CREATE PROCEDURE spTest AS RETURN
GO
ALTER PROCEDURE spTest
AS
BEGIN
SET NOCOUNT OFF
DECLARE #rt int
CREATE TABLE #t (
v int NOT NULL
)
INSERT INTO #t (v)
SELECT v FROM (VALUES (1), (1), (2)) AS t (v)
SET #rt = ##ROWCOUNT
DROP TABLE #t
RETURN #rt
END
GO
DECLARE #rt int
EXEC #rt = spTest
SELECT #rt
GO
DROP PROCEDURE spTest
GO

I would use an output param something like.....
ALTER PROCEDURE [dbo].[SaveTextSetting]
#UserId INT ,
#SettingType INT = 0 ,
#SettingValue NVARCHAR(MAX),
#RowCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM Settings
WHERE UserId = #UserId
AND SettingType = #SettingType;
EXEC dbo.PurgeExpiredSettings;
INSERT INTO dbo.Settings( UserId ,SettingsText ,SettingType)
VALUES ( #UserId ,#SettingValue ,#SettingType);
SET #RowCount= ##ROWCOUNT;
END

Related

Create trigger in stored procedure

I am trying to create a trigger inside stored procedure as it will be removed when the table is dropped.
I am getting an error and am not able to execute it.
CREATE PROCEDURE EC5Trigger2
AS
CREATE TRIGGER trVendorProductsPST
ON VendorProducts
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
DECLARE #SKU VARCHAR(64)
SELECT #SKU = I.SKU FROM inserted AS I
INSERT INTO ProductStockTransactions (SKU, stockingCode)
VALUES (#SKU, 'A')
END
RETURN 0
Here is how you create your trigger inside a stored procedure using dynamic SQL, which is the only way to do it.
CREATE PROCEDURE EC5Trigger2
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TriggerCode NVARCHAR(max);
SET #TriggerCode = 'CREATE TRIGGER trVendorProductsPST
ON VendorProducts
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
DECLARE #SKU VARCHAR(64)
SELECT #SKU = I.SKU from INSERTED as I
INSERT INTO ProductStockTransactions (SKU, stockingCode)
VALUES (#SKU, ''A'')
END';
EXEC(#TriggerCode);
RETURN 0;
END;

SQL SERVER : How to execute an SP specifed number of time without using loop

I have a scenario wherein i have to execute an SP for specified number of time(number of execution will be mentioned by user) without using loop.
My SP is setting an OUTPUT variable of varchar type. I am willing to insert the output of my SP into a temp table and use it for further processing.
I am unable to modify this SP into function as it contain an Update statement.
Kindly suggest if we can do so without loop.
Whit this solution you do not need an output; #res is your result directly set in a temp table.
CREATE PROCEDURE [dbo].[myStoredProc]
#Counter int,
#params nvarchar(64),
#CreateTable bit
AS
DECLARE #res varchar(64)
IF #CreateTable = 1
BEGIN
IF EXISTS (SELECT 1 FROM dbo.sysobjects WHERE id = object_id(N'[#tempTable]'))
DROP TABLE #tempTable
CREATE TABLE #tempTable ([Res] [nvarchar] (64))
END
SET #res = CONVERT(varchar(64), #Counter)
SET #Counter = #Counter - 1
IF #Counter > 0
exec myStoredProc #Counter, #params, 0
INSERT #tempTable VALUES (#res)
IF #CreateTable = 1
BEGIN
SELECT * FROM #tempTable
DROP TABLE #tempTable
END
GO
DECLARE #o varchar(64)
exec [myStoredProc] 5, '', 1

Retrieving a particular value in SQL Server

I have this stored procedure that has a value:
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
DECLARE #return_value int
DECLARE #media_id uniqueidentifier
'INSERT SQL STATEMENT HERE
SELECT [media_id] FROM [media] WHERE 1 = 1
-- One row affected
RETURN 1
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
-- Rollback, no row affected
RETURN 0
END CATCH;
I want to call the [media_id] value from another stored procedure. How do I get that value?
Table Definition
CREATE TABLE MY_EMPLOYEE
(EMPID INT, NAME VARCHAR(20),
LANGUAGEID INT , ID UNIQUEIDENTIFIER DEFAULT NEWID())
GO
Stored Procedure
ALTER PROCEDURE usp_ProcName
#Emp_ID INT = null,
#Name VARCHAR(20) = null,
#LanguageID int = null,
#NewID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
INSERT INTO [Practice_DB].[dbo].[MY_EMPLOYEE](EMPID, NAME, LANGUAGEID)
VALUES (#Emp_ID, #Name, #LanguageID);
-- Populating the OUTPUT variable using the other variables that were passed
-- for INSERT statement.
SELECT #NewID = ID
FROM [Practice_DB].[dbo].[MY_EMPLOYEE]
WHERE EMPID = #Emp_ID
-- One row affected
COMMIT TRANSACTION
RETURN 1
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
-- Rollback, no row affected
RETURN 0
END CATCH
END
GO
Calling Stored Procedure
DECLARE #value int, #ID VARCHAR(100)
EXECUTE #value = usp_ProcName
#Emp_ID = 50,
#Name = 'John',
#LanguageID = 50,
#NewID = #ID OUTPUT --<-- passing this variable with OUTPUT key word this will be
-- populated inside the Procedure and then you can SELECT it or
-- whatever you want to do with this value.
SELECT #ID
SELECT #value
This should help: Return Data from a Stored Procedure
I think this should work
BEGIN TRY
BEGIN TRANSACTION;
-- Insert statements for procedure here
DECLARE #return_value int
DECLARE #media_id uniqueidentifier
--get the value from the stored procedure here
Declare #SQL varchar(max)
set #SQL='INSERT SQL STATEMENT HERE
SELECT #media_id FROM [media] WHERE 1 = 1'
exec #SQL
-- One row affected
RETURN 1
END TRY

Return Output Param of a Stored Procedure inside another Stored Procedure

I'm trying to find out how to return the output parameter of a stored procedure when executing the stored procedure inside another stored procedure:
CREATE PROCEDURE Test1
EXEC SpWithOutputID -- Outputs #ID
SELECT #ID as ID -- Output #ID now being used in this SP
This is of course not my code, but just an example, is it possible to do this?
Example 2:
--Here #ID returns Null
CREATE PROCEDURE Test1
As
DECLARE #ID int
EXEC SpWithOutputID #ID = #ID OUTPUT -- Outputs #ID
SELECT #ID as ID -- Output #ID now being used in this SP
Example 3:
--Here #ID returns an Int
CREATE PROCEDURE Test1
As
EXEC SpWithOutputID -- Outputs #ID
If this isn't really an output parameter issue at all, but rather a result set, then taking a guess that SpWithOutputID does something like this (returns a SELECT with a single row and single column):
CREATE PROCEDURE dbo.SpWithOutputID
AS
BEGIN
SET NOCOUNT ON;
SELECT ID = 4;
END
GO
Then Test1 could look like this:
CREATE PROCEDURE dbo.Test1
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ID INT;
CREATE TABLE #x(ID INT);
INSERT #x EXEC dbo.SpWithOutputID;
SELECT TOP (1) #ID = ID FROM #x;
DROP TABLE #x;
END
GO
But doesn't that look really messy to you? It really should work this way for single, scalar values:
CREATE PROCEDURE dbo.SpWithOutputID
#ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #ID = 4;
END
GO
Now it is much simpler to consume what is really an output parameter now:
CREATE PROCEDURE dbo.Test1
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ID INT;
EXEC dbo.SpWithOutputID #ID = #ID OUTPUT;
SELECT #ID;
END
GO

Call Stored Procedure within Create Trigger in SQL Server

I have a stored procedure named insert2Newsletter with parameters
(#sex nvarchar(10),
#f_name nvarchar(50),
#l_name nvarchar(70),
#email nvarchar(75),
#ip_address nvarchar(50),
#hotelID int,
#maArt nchar(2))
I want call this stored procedure in an insert trigger. How do I retrieve the corresponding fields from inserted and how do i call insert2Newsletter within the trigger?
I tried without success:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER RA2Newsletter
ON [dbo].[Reiseagent]
AFTER INSERT
AS
DECLARE #rAgent_Name nvarchar(50),
DECLARE #rAgent_Email nvarchar(50),
DECLARE #rAgent_IP nvarchar(50),
DECLARE #hotelID int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select #rAgent_Name=rAgent_Name, #rAgent_Email=rAgent_Email, #rAgent_IP=rAgent_IP, #hotelID=hotelID From Inserted
EXEC insert2Newsletter '','',#rAgent_Name,#rAgent_Email,rAgent_IP,#hotelID,'RA'
END
GO
thx a lot for your feedback... greetings...
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE #rAgent_ID INT = 0
-- Looping variable.
DECLARE #i INT = 0
-- Count of rows affected for looping over
DECLARE #count INT
-- These are your old variables.
DECLARE #rAgent_Name NVARCHAR(50)
DECLARE #rAgent_Email NVARCHAR(50)
DECLARE #rAgent_IP NVARCHAR(50)
DECLARE #hotelID INT
DECLARE #retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT #Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE #i < #count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
#rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > #rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT #rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = #rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', #rAgent_Name, #rAgent_Email,
#rAgent_IP, #hotelID, 'RA', #retval
-- Set up next iteration
SET #i = #i + 1
END
END
GO
I sure hope this helps you out. Cheers!
Finally ...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[RA2Newsletter]
ON [dbo].[Reiseagent]
AFTER INSERT
AS
declare
#rAgent_Name nvarchar(50),
#rAgent_Email nvarchar(50),
#rAgent_IP nvarchar(50),
#hotelID int,
#retval int
BEGIN
SET NOCOUNT ON;
-- Insert statements for trigger here
Select
#rAgent_Name = rAgent_Name,
#rAgent_Email = rAgent_Email,
#rAgent_IP = rAgent_IP,
#hotelID = hotelID
From Inserted
EXEC insert2Newsletter
'',
'',
#rAgent_Name,
#rAgent_Email,
#rAgent_IP,
#hotelID,
'RA',
#retval
END
The following should do the trick - Only SqlServer
Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN
SET NOCOUNT ON;
Declare #id int
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
select #id=deleted.Catagory_id from deleted
print #cDate
execute dbo.psp_Update_Category #id
END
Alter PROCEDURE dbo.psp_Update_Category
#id int
AS
BEGIN
DECLARE #cDate as DateTime
set #cDate =(select Getdate())
--Update Catagory_Master Set Modify_date=''+#cDate+'' Where Catagory_ID=#id --#UserID
Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END
You pass an undefined rAgent_IP parameter in EXEC instead of the local variable #rAgent_IP.
Still, this trigger will fail if you perform a multi-record INSERT statement.

Resources