Trying to create a simple trigger SQL Server 2005 - 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

Related

How can I assign an exec result to multiple sql variables?

I got the returned data after executing a stored procedure named [s_sspCallSharePointWebService] in SSMS
DECLARE #sWebAddr AS NVARCHAR(MAX),
#bAPISuccess AS NVARCHAR(10),
#objSharePointXML AS XML
SET #sWebAddr = 'http://...'
EXEC [s_sspCallSharePointWebService] #sWebAddr, #bAPISuccess OUTPUT, #objSharePointXML OUTPUT
I was wondering how do I save
the data in variables instead of returning a table below.
---------------------------------------
| (No column name) | (No column name) |
---------------------------------------
| True | <XMLRoot>.... |
---------------------------------------
Additionally, I cannot insert the data into a temp table here because I had the result of EXEC sp_OAGetProperty #objecttoken, 'responseText' in [s_sspCallSharePointWebService], and then already inserted the response text into a temp table.
That would cause an error:
An INSERT EXEC statement cannot be nested
It is very ugly (for me), but this can be done using temporary tables. The temporary table is visible to all routines in the current scope.
So, you can have nesting like this:
EXEC SP1
...
EXEC SP2
...
EXEC SP3
...
and let's say EXEC SP2 is returning a row set executing a SELECT statement. So, the question is how to materialized it?
CREATE PROCEDURE dbo.SP1
AS
BEGIN;
SELECT 'SP1' AS [Caller];
EXEC dbo.SP2;
END;
GO
CREATE PROCEDURE dbo.SP2
AS
BEGIN;
SELECT 'SP2' AS [Caller];
INSERT INTO #TEST
SELECT 1;
END;
GO
CREATE TABLE #TEST
(
[ID] INT
);
EXEC dbo.SP1;
SELECT *
FROM #TEST;
The idea is to create the temporary table in the outer scope and the procedure to be sure that this table is already created and populate it. Then, use the table in the initial caller.
It's ugly for me, because if this table is not defined the routine will cause an error:
Msg 208, Level 16, State 0, Procedure dbo.SP2, Line 8 [Batch Start
Line 0] Invalid object name '#TEST'.
and it can be difficult to debug in some cases.
Instead of doing that, you can just use a table variable, and then SELECT from it to assign. Here's an example with a simple proc that returns a single row:
USE tempdb;
GO
CREATE OR ALTER PROC dbo.ReturnsOneRow
AS
BEGIN
SELECT 1 AS FirstColumn, 'Hello' AS SecondColumn, 4 AS ThirdColumn;
END;
GO
EXEC dbo.ReturnsOneRow;
GO
DECLARE #FirstColumn int;
DECLARE #SecondColumn varchar(20);
DECLARE #ThirdColumn int;
DECLARE #Row TABLE
(
FirstColumn int,
SecondColumn varchar(20),
ThirdColumn int
);
INSERT #Row
(
FirstColumn, SecondColumn, ThirdColumn
)
EXEC dbo.ReturnsOneRow;
SELECT TOP(1) #FirstColumn = r.FirstColumn,
#SecondColumn = r.SecondColumn,
#ThirdColumn = r.ThirdColumn
FROM #Row AS r;
-- Check the values
SELECT #FirstColumn, #SecondColumn, #ThirdColumn;
The table variable will be way better than a temp table in this situation, and you don't have issues with its visibility elsewhere, or having to clean it up (it's gone at the end of the batch).

Calling a stored procedure from another procedure

Using this table variable:
DECLARE #ReturnValue VARCHAR
DECLARE #OUT_MAIN_ERROR VARCHAR
DECLARE #Result VARCHAR(50)
BEGIN
DECLARE #TableVariable TABLE (result VARCHAR(50))
INSERT INTO #TableVariable
EXEC [dbo].[DRIVEPOOL2]
SELECT result
FROM #TableVariable
END
Using temp table:
DECLARE #ReturnValue VARCHAR
DECLARE #OUT_MAIN_ERROR VARCHAR
DECLARE #Result VARCHAR(50)
BEGIN
CREATE TABLE #kola(result VARCHAR(50))
INSERT INTO #kola
EXEC [dbo].[DRIVEPOOL2]
SELECT *
FROM #kola
DROP TABLE #kola
END
I get error:
Msg 8164, Level 16, State 1, Procedure DRIVEPOOL2, Line 45 [Batch Start Line 3]
An INSERT EXEC statement cannot be nested.
I have tried with both temp table and table variable, both are throwing the error that the INSERT EXEC statement can't be nested.
Drive Pool Procedure for Reference - Github
Seems to be duplicate with this thread: INSERT EXEC Statement cannot be nested
This error occurs when calling a stored procedure and inserting the
result of the stored procedure into a table or table variable (INSERT
... EXECUTE) and the stored procedure being called already contains an
INSERT ... EXECUTE statement within its body.
Read more about this error here:http://www.sql-server-helper.com/error-messages/msg-8164.aspx
You can try OPENROWSET to overcome this problem
INSERT INTO #TableVariable ( col1, col2, col3,... )
SELECT SP.*
FROM OPENROWSET('SQLNCLI', '[Your connection string]','EXECUTE [dbo].[DRIVEPOOL2]') AS SP

Renaming a column of a Table in SQL Server FAILS

I declare a table in a stored procedure and then try to rename one of the columns of the table but it fails:
-- create the finaltable
declare #finaltable table(data_date datetime, ind_value float)
Insert into #finaltable (data_date)
select distinct l.value_date
from #data_table l
order by l.value_date
---some code here that works
exec sp_rename '#finaltable.ind_value', 'NewValue', 'COLUMN' --
This part fails
What am I doing wrong?
Error Message:
Msg 15248, Level 11, State 1, Procedure sp_rename, Line 215
Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.

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?

create trigger using a stored procedure

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.