Create trigger in stored procedure - sql-server

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;

Related

How to insert a field of a procedure result in a variable?

I have a procedure dbo.pX that returns a table with 1 field named id and an INT in it, that can be equal to 0, or another positive integer. I need to insert this id in a variable inside a procedure named dbo.pY, to verify if the id is greater than 0.
Procedure dbo.pX:
CREATE PROCEDURE dbo.pX
#param1 VARCHAR(30)
AS
DECLARE #id INT;
-- Some code to change the #id
SELECT #id AS 'id';
GO
What I tried to do in dbo.pY:
CREATE PROCEDURE dbo.pY
#param1 VARCHAR(30)
AS
DECLARE #ret INT;
SET #ret = (EXECUTE dbo.pX 'something');
IF ( #ret > 0 ) BEGIN
-- Some code that uses #ret
END
GO
Any tips or hints to help me find a way to solve it?
Obs: I can't change the procedure dbo.pX.
As I know the fields that the procedure was bringing me, and I couldn't change that procedure, I solve it like this:
CREATE PROCEDURE dbo.pY
#param1 VARCHAR(30)
AS
-- insert the procedure table inside a temporary table
DECLARE #temp TABLE (id INT);
INSERT INTO #temp EXECUTE dbo.pX 'something';
-- insert id that the table brings in a variable
DECLARE #ret INT;
SELECT #ret = id FROM #temp;
IF ( #ret > 0 ) BEGIN
-- Some code that uses #ret
END
GO
Problem solved :)

How to pass a view name to a stored procedure in SQL Server 2014

CREATE PROCEDURE [dbo].[sp_HeatMap_Paper]
#Grade varchar(150)=NULL,
#Site varchar(250)=NULL,
#TRef varchar(15)=NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #uregref varchar(50), #regTID varchar(8),
#testValue varchar(80), #testResultID int,
#lowerL1 varchar(20), #upperL1 varchar(20),
#lowerL2 varchar(20), #upperL2 varchar(20)
BEGIN TRANSACTION
BEGIN TRY
DELETE FROM HeatMap;
select top 1 #uregref = URegRef from NA_PAPER_HEAT_MAP where RSDESCRIPTION= #Grade and BOX_PLANT1= #Site;
select #regTID = RegTID from REGKEY where URegRef = #uregref;
select #testValue=TestResult,#testResultID=Result_ID from RESULTDATA where RegTID=#regTID and TRef=#TRef;
SELECT #lowerL1=Lower, #upperL1=Upper from ResultLimit WHERE Priority = 1 and Result_Id=#testResultID;
SELECT #lowerL2=Lower, #upperL2=Upper from ResultLimit WHERE Priority = 2 and Result_Id=#testResultID;
Insert into HeatMap (Grade,Site,TestValue,TRef,LowerLimitL1,UpperLimitL1,LowerLimitL2,UpperLimitL2)
values (#Grade,#Site,#testValue,#TRef,#lowerL1,#upperL1,#lowerL2,#upperL2)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
Return Error_Message()
END CATCH
END
GO
I want to pass a view name into this stored procedure, here 'NA_PAPER_HEAT_MAP' is the view instead of this I want to pass a parameter #viewName
You can build dynamic SQL and execute it using sys.sp_executesql to execute it.
I'll give you an example for how to use it.
CREATE PROCEDURE usp_selectView
#id INT,
#viewName NVARCHAR(1000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX), #paramDef NVARCHAR(MAX);
-- build dynamic SQL
-- you can build whatever SQL you want. This is just an example
-- make sure you sanitize #viewName to avoid SQL injection attack
SET #sql = 'SELECT * FROM ' + #viewName + ' WHERE Id = #selectedId';
-- dynamic SQL parameter definition
SET #paramDef = '#selectedId INT';
-- here, execute the dynamic SQL
EXEC sys.sp_executesql #sql, #paramDef, #selectedId = #id
END

Getting rows affected in stored procedure INSERT statement with NOCOUNT OFF

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

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

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