create trigger using a stored procedure - sql

I have a trigger and I want to kick it off from a stored procedure. I am using ms access and when i run the trigger from ms access it gives me an error msg (ODBC). I think I can't create triggers using ms access. This is my trigger:
IF EXISTS
(SELECT name
FROM sys.objects
WHERE name = 'UpdateComments' AND type = 'TR')
DROP TRIGGER tblEmailHdr_abenit01.UpdateComments;
GO
CREATE TRIGGER UpdateComments
ON tblEmailHdr_abenit01
AFTER Update
AS
IF ( UPDATE (Comments) ) BEGIN Update ttblEmailHdr_abenit01
Set UpdateComm = GetDate()
END;
GO
This is how I have been trying to create the trigger from the stored procedure but I get the following error msg's when I try to create the sproc:
Sproc:
CREATE PROCEDURE dbo.SP_AS_tblEmailHdr_Trig (#UserID as varchar(10))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #UserTable Varchar(50)
Declare #UserTable2 Varchar(50)
Set #UserTable = 'tblEmailHdr_' + #UserID ;
Set #UserTable2 = 'tblEmailHdr_' + #UserID + '.UpdateComments' ;
IF EXISTS
(SELECT name
FROM sys.objects
WHERE name = 'UpdateComments' AND type = 'TR') DROP TRIGGER #UserTable2
GO
CREATE TRIGGER UpdateComments
ON #UserTable
AFTER UPDATE
AS
IF ( UPDATE (Comments) )
BEGIN
--RAISERROR (50009, 16, 10)
Update #UserTable
Set UpdatedComm = GetDate()
END
GO
END
GO
error msg i get:
Msg 102, Level 15, State 1, Procedure SP_AS_tblEmailHdr_Trig, Line 23
Incorrect syntax near '#UserTable2'.
Msg 102, Level 15, State 1, Procedure UpdateComments, Line 2
Incorrect syntax near '#UserTable'.
Msg 1087, Level 15, State 2, Procedure UpdateComments, Line 8
Must declare the table variable "#UserTable".
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.

create procedure pro (parameters)
as
begin
declare #trigs nvarchar(max)
declare #trip nvarchar(max)
set #trigs='
create trigger tri on dbo.employee
for insert
as
select * from inserted
go'
set #trip='drop trigger tri'
EXEC sp_executeSQL #trigs
insert into employee values(parameters)
EXEC sp_executeSQL #trip
end
exec pro param
eg:
exec pro 80,'aaa','AAS',25000,'2013-02-01','iT'

remove all the GO statements from inside the procedure.

Related

Use stored procedure in values of an Insert statement

I'm trying to use a stored procedure in an insert statement this is my code:
EXEC sp_executesql #statement=N'insert into Celulares_Empleados(CEL_IMEI,Empl_ID,FH_Asignacion,US_Asigno)
values (#imei, EXEC EMPLEADOS_LEGAJOS #legajo, #date, #usuario)',
#params=N'#imei nvarchar(15), #legajo nvarchar(41), #date datetime, #usuario nvarchar(5)',
#imei=N'353108089985778',
#legajo=N'USUARIO DE PRUEBA - Legajo: 1171',
#date='2020-06-18 22:56:08.367',
#usuario=N'admin'
But I get this message:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'EXEC'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.
I also tried to put the Exec statement between ( ) but I get the same error.
Is there a way to do that?
You cannot call stored procedure as part of VALUES clause in INSERT. What you can do is, first execute the stored procedure and get the return value in a variable. Use the variable as part of your sp_executesql procedure call.
DECLARE #p_Empl_ID int
DECLARE #legajo NVARCHAR(41)= N'USUARIO DE PRUEBA - Legajo: 1171'
EXEC #p_Empl_ID = EXEC EMPLEADOS_LEGAJOS #legajo
EXEC sp_executesql #statement=N'insert into Celulares_Empleados(CEL_IMEI,Empl_ID,FH_Asignacion,US_Asigno)
values (#imei,#Empl_ID , #date, #usuario)',
#params=N'#imei nvarchar(15), #legajo nvarchar(41), #date datetime, #usuario nvarchar(5)',
#imei=N'353108089985778',
#Empl_ID = #p_Empl_ID ,
#date='2020-06-18 22:56:08.367',
#usuario=N'admin'
NOTE: Generally, best practice is to, return the execution status of the procedure as return value. If you want to get some scalar value out of procedure execution, it is preferred to use output parameter and use them in subsequent stages.
DECLARE #p_Empl_ID int
DECLARE #legajo NVARCHAR(41)= N'USUARIO DE PRUEBA - Legajo: 1171'
EXEC EMPLEADOS_LEGAJOS #legajo, #p_Empl_ID OUTPUT

How to save stored procedure output into table

I am new to T-SQL so I apologize if I am stating my question wrong.
I have a SQL Server stored procedure that has properties and returns integer value also selects some columns from different tables.
I was wondering how can I store that result into regular table
DECLARE #prop1 int;
DECLARE #prop2 int;
DECLARE #result int;
set #prop1 = 2
set #prop2 = 5
exec #result = dbo.Proc1 #prop1 #prop2
Result:
id name value
---------------------
1 Example 6
2 Process 8
.. ........ ..
Thank you in advance for all your input.
//-----------Edit 04/22/2015---------------------------
I am trying to use T-SQL below:
SELECT * INTO Tx.ReportFacts FROM OPENROWSET('SQLNCLI', 'Server=GCA_A;Trusted_Connection=yes;',
'SET NOCOUNT ON;SET FMTONLY OFF; EXEC #RC = ReportLibrary.Rpt.Server_GetAllDiscrepancies #FacilityKey ,#StationKeys ,#MedItemKeys ,#MedClassCodes ,#UserAccountKeys ,#ResolutionStatus ,#TransactionLimit ,#ReportStartDate ,#ReportEndDate')
-- Select Table
SELECT *
FROM Tx.ReportFacts;
But getting error below:
OLE DB provider "SQLNCLI11" for linked server "(null)" returned message "Deferred prepare could not be completed.".
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#RC".
Can anyone point out why this is happening. And what is wrong with my T-SQL statement?
You can use insert - exec.
Try this:
insert into table_name
exec dbo.Proc1 #prop1 #prop2;

SQL - If Parameters within Stored Procedure

I am trying to get a complex stored procedure to work, but I can't figure out the relationship between stored procedures, parameters and IF/THEN statements.
I have stripped my code down to the attached chunk of code, that shows where I am going wrong. When I execute it, I get an error
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'and'
Basically, I have 3 variables - #Test1, #Test2 and #Test3. These are prompts that appear when you execute the stored procedure. If the user enters '1', '2', '3' respectively, it should show the text 'Show 1 and 2 and 3 Plus Pivot Section'. If the only enter '1','2' it should show the text 'Show 1 and 2 Plus Pivot Section'.
Below is my code, am I doing something wrong??
ALTER PROCEDURE [dbo].[sp_Data_Extract_Test]
#Test1 [NVARCHAR] (400),
#Test2 [NVARCHAR] (400),
#Test3 [NVARCHAR] (400)
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Output NVARCHAR(400) ;
Declare #param NVARCHAR(900) ;
Set #param = '#Test1 nvarchar(400), #Test2 nvarchar(400), #Test3 nvarchar(400)'
if (#Test1 = '1')
BEGIN
SET #Output = 'Show 1';
END
if (#Test2 = '2')
BEGIN
SET #Output = #Output + ' and 2';
END
if (#Test3 = '3')
BEGIN
SET #Output = #Output + ' and 3';
END
BEGIN
SET #Output = #Output + ' Plus Pivot Section'
PRINT #Output
END
EXECUTE SP_EXECUTESQL #Output, #param, #Test1, #Test2, #Test3;
END
Edit: My example above isn't a good example. I was trying to narrow it down to identify the problem, but it seems as though the Execute statement at the bottom expects a SQL statement, not a line of text.
What I am trying to do, is effectively the following. I want to execute a stored procedure that pivot's a data set. The data is built up by 2 appends (unions) that are based on prompts. I want it so that the user can potentially run it for 1 type of Quantity, for 2, or for 3. If they want to see all 3 Quantities, it needs to do 2 appends. The code is as below. I've added XXX's where the SQL statement is because I know those parts are working fine, it's only when I try to do this if statement based on variables so I can potentially filter off the unions.
--- Above: Alter Stored Procedure, with variable declarations
declare #V1 NVARCHAR(4000) ;
declare #param NVARCHAR(900) ;
set #param='XXXXXX'
if (#Value1 = 'Qty_Ordered')
BEGIN
set #V1='SELECT XXXXXX’
END
if (#Value1 = 'Qty_Ordered' and #Value2 = 'Qty_Supplied')
BEGIN set #V1= #V1 + '
UNION ALL
SELECT XXXXX'
END
if ((#Value1 = 'Qty_Ordered' or #Value2 = 'Qty_Supplied') and #Value3 = 'Qty_Forecast')
BEGIN set #V1= #V1 +
'UNION ALL
SELECT XXXXXX’
END
BEGIN
set #V1 = #V1 + '
PIVOT
(
SUM([Value])
FOR p.forecast_Week_No IN ('+#cols1+','+#cols2+','+#cols3+')) AS pvt'
END
EXECUTE SP_EXECUTESQL #V1, #param, XXXXXXXX;
END
The frist paramenter for sp_executesql should be a TSQL statement, but #Output does not represent that.
If your intention was only to print the message then comment EXECUTE
SP_EXECUTESQL #Output, #param, #Test1, #Test2, #Test3;
Now regarding Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'and'
sqlserver basically checked for syntax error in the TSQL stmt passed through #Output,
what it got was "Show 1 and 2 and 3 Plus Pivot Section"
As SHOW is not a SQL stmt, it considered it as a stored proc,
next it looked at 1, and 1 it is allowed as a paramenter
next it got "and", it is not accepted to used words like "and" while executing a SP
so gave a syntax error Msg 156, Level 15, State 1...

Trying to create a simple trigger SQL Server 2005

I'm trying to create a simple trigger just like an audit.
The error is
Msg 102, Level 15, State 1, Procedure sampleTrigger, Line 13
Incorrect syntax near '#OLDName'.
Can anyone help me ?
Here's my sample code .
CREATE TRIGGER sampleTrigger
ON tblEmployee
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
declare #OLDName varchar(50)
declare #NewName varchar(50)
Select #OLDName = EmployeeName from deleted
Select #NewName = EmployeeName from inserted
insert into Audit
values (Getdate()#OLDName, #NewName)
END
GO
To fix the syntax, you're simply missing a comma;
insert into Audit
values (Getdate(), #OLDName, #NewName)
^ this one

Error in SQL Server 2005 stored procedure

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Prc_InsertUpdate] (#boxone VARCHAR(200),
#boxtwo VARCHAR(200),
#boxthree VARCHAR(200))
AS
DECLARE #num AS INT
SELECT #num = MAX(NUMBER) + 1
FROM updatepage
INSERT INTO [TestDB].[dbo].[updatepage]
([number],
[box1],
[box2],
[box3])
VALUES (#num,
#boxone,
#boxtwo,
#boxthree)
I'm creating this procedure but got this error
Msg 208, Level 16, State 6, Procedure Prc_InsertUpdate, Line 9
Invalid object name 'dbo.Prc_InsertUpdate'.
You are ALTER-ing a stored procedure that does not exist. Use CREATE procedure [dbo].[Prc_InsertUpdate] instead.
Also why isn't number an identity column? Your current approach is inefficient and not safe under conditions of concurrency?