Create trigger error: 'Incorrect Syntax near 'dbo' - sql

I'm currently learning some regarding SQL triggers. I am trying to create a column on a test table which will show the current date when the row is updated. The column datatype is type DateTime So far I have:
CREATE TRIGGER lastUpdated
ON [dbo].[ImportTest]
AFTER UPDATE
AS
BEGIN
IF NOT UPDATE(LAST_UPD)
BEGIN
SET [dbo].[ImportTest].[LAST_UPD] = CURRENT_TIMESTAMP
END
END
GO
However, I get the following error trying to execute:
Msg 102, Level 15, State 1, Procedure lastUpdated, Line 29
Incorrect syntax near 'dbo'.
Any help would be appreciated.

You cannot update a column like assigning value to variable. Try this
IF NOT UPDATE(LAST_UPD)
BEGIN
UPDATE IT
SET [LAST_UPD] = CURRENT_TIMESTAMP
FROM [dbo].[ImportTest] IT
WHERE EXISTS (SELECT 1
FROM inserted i
WHERE i.somecol = it.somecol
And ...)
END

Related

Msg 178, Level 15, State 1, Line 8 A RETURN statement with a return value cannot be used in this context

I received this error message while trying to execute below SQL.
Error:
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'FUNCTION'.
Msg 178, Level 15, State 1, Line 8
A RETURN statement with a return value cannot be used in this context.
SQL:
IF (NOT EXISTS (SELECT * FROM DBO.TRACKING WHERE CR = 123))
BEGIN
CREATE FUNCTION [dbo].[UDFDate]()
RETURNS DATETIME
AS BEGIN
RETURN CAST('9999-12-31' AS DATETIME)
END
END
Am I not allowed to create a Function inside if statement ?
There are no reasons why you would want to create functions inside a stored procedure during runtime. Functions in SQL SERVER work similarly to stored procedures, so if you want to create a function you need to do it outside of the context and scope of a stored procedure and it will be saved on your database to be accessed at any time.
Ontopic, if you only want to exhibit that date value you could just remove the function creation and select the datetime result as this:
IF (NOT EXISTS (SELECT TOP 1 1 FROM DBO.TRACKING WHERE CR = 123))
BEGIN
SELECT CAST('9999-12-31' AS DATETIME)
END
PS: Don't use "SELECT *" when you just want to know if some value exists. It creates unnecessary overhead to bring all columns when you just want to know if anything exists.
You cannot create a function inside an if statment this way you will get the following warning
Incorrect syntax: CREATE FUNCTION must be the only statment in the batch
you can do it by creating a variable stor the create query in this variable and execute it:
IF (NOT EXISTS (SELECT * FROM DBO.TRACKING WHERE CR = 123))
BEGIN
DECLARE #strQuery AS VARCHAR(MAX)
SET #strQuery = '
CREATE FUNCTION [dbo].[UDFDate]()
RETURNS DATETIME
AS BEGIN
RETURN CAST(''9999-12-31'' AS DATETIME)
END
'
EXEC(#strQuery)
END
but i didn't understand why creating a function to return a static value??!!

SQL printing error message with bad record code

Working with SQL Server 2005
Creating Trigger which checks if inserting not already exist.
Having problem getting record parameter, there is the code:
CREATE TRIGGER t_MFShiftTypeOperation ON [CAST$MFShiftTypeOperation]
FOR INSERT, UPDATE AS
IF ##ROWCOUNT=1
BEGIN
IF EXISTS (SELECT * FROM inserted AS I
JOIN CAST$MFShiftTypeOperation AS STO
ON ((I.ShiftTypeCode = STO.ShiftTypeCode AND
I.PackCode = STO.PackCode) OR
I.RegisterAppCode = STO.RegisterAppCode))
BEGIN
DECLARE #Bad_PackCode AS EmpUserCode_t
SET #Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error
ROLLBACK TRAN
PRINT 'Оperation with '+ #Bad_PackCode +' already exist'
END
END
when I'm trying to execute code, it throws me error message:
Msg 156, Level 15, State 1, Procedure t_MFShiftTypeOperation, Line 16
Incorrect syntax near the keyword 'SELECT'.
Can someone explain where is mistake, or suggest better solution.
Change this line:
SET #Bad_PackCode = SELECT TOP(1) PackCode FROM inserted --there is error
to this:
SELECT TOP(1) #Bad_PackCode=PackCode FROM inserted

Need to create triggers for audit tracking, getting "incorrect syntax?"

I have one table Products on which i need to create trigger to update changes (new data) in data in another table Products_audit which has same columns with same data.
I've tried following:
CREATE TRIGGER Super
ON Products
AFTER INSERT, UPDATE
AS
UPDATE Product_audit (Column1,Column2, Column3, ... )
SELECT (Column1,Column2,Column3,...)
FROM Products
Receiving the following error:
Server: Msg 170, Level 15, State 31, Procedure Super, Line 20
Line 20: Incorrect syntax near '('.
Server: Msg 170, Level 15, State 1, Procedure Super, Line 24
Line 24: Incorrect syntax near ','.
I use sql server 2000
I'm not so strong else in triggers creation could you please correct me I'd like to know where was I wrong ?
I think you trigger need to look like this:
CREATE TRIGGER Super
ON Products
AFTER INSERT, UPDATE
AS
UPDATE Product_audit
SET Column1 = p.Column1
SET Column2 = p.Column2
FROM Products p
Hello you have to create two different trigger one for update and one for insert
1) For Insert
CREATE TRIGGER Super
ON Products
AFTER INSERT
AS
BEGIN
INSERT INTO Product_audit
(Column1,Column2,...)
SELECT Column1,Column2,...
FROM Inserted
END
2) For Update
CREATE TRIGGER Super
ON Products
AFTER Update
AS
BEGIN
DECLARE #Column1 as varchar(10)
DECLARE #Column2 as varchar(10)
DECLARE #ID INT
SELECT #ID=ID,#Column1=Column1,#Column2=Column2 FROM INSERTED
UPDATE Product_audit SET Column1=#Column1,Column2=#Column2
WHERE ID=#ID
END

Transact SQL - Rollback, Variable Scope, Exiting

The somewhat minimal minimal version of what I'm trying to do boils down to this:
declare #VERSION_TO NVARCHAR(255);
declare #VERSION_CURRENT NVARCHAR(255);
set #VERSION_TO = '3.0.4401';
select #VERSION_CURRENT = VERSION from T_SYSTEM_INFO;
print 'target version: ' + #VERSION_TO
print 'current version: ' + #VERSION_CURRENT
if not #VERSION_CURRENT IN ('3.0.4300')
begin
raiserror( 'Patch not possible - unknown predecessor "%s"', 17, 10, #VERSION_CURRENT)
return
end
alter table T_JOB add CREATED [datetime];
update T_JOB set CREATED = (select top 1 STEP_START from T_JOB_STEP where T_JOB_STEP.JOB = T_JOB.ID and T_JOB_STEP.ID not in (select STEP from T_JOB_STEP_DEPENDENCY));
update T_JOB set CREATED = '01-01-2000' where T_JOB.CREATED is null;
alter table T_JOB alter column CREATED [datetime] not null;
update T_SYSTEM_INFO set VERSION = #VERSION_TO;
go
but it fails on the update after the first ALTER TABLE:
Msg 207, Level 16, State 1, Line 0
Invalid column name 'CREATED'.
if I put a 'go' after the ALTER TABLE, it works, but fails on the last UPDATE:
Msg 137, Level 15, State 2, Line 7
Must declare the scalar variable "#VERSION_TO".
I understand the scope of variables is limited by the go statements. I only want to have one at the end, anyways, so changes are rolled back if anything goes wrong. And if none of this is possible, how can I exit the whole script if there is an error, not just the transaction?
could anybody google the answer for me, please? :)
thanks
Can you not just redefine #VERSION_TO and set it after your alter table DDL?
NOTE: transactions and DDL don't mix, i.e. you can't rollback an alter table.
Have you looked at sqsh? it is a SQL "shell" to replace isql that could help a lot here.

Stored Procedure consist Add column, Update data for that column, and Select all data from that table

I've written a stored procedure as following:
CREATE PROC spSoNguoiThan
#SNT int
AS
begin
IF not exists (select column_name from INFORMATION_SCHEMA.columns where
table_name = 'NhanVien' and column_name = 'SoNguoiThan')
ALTER TABLE NhanVien ADD SoNguoiThan int
else
begin
UPDATE NhanVien
SET NhanVien.SoNguoiThan = (SELECT Count(MaNguoiThan)FROM NguoiThan
WHERE MaNV=NhanVien.MaNV
GROUP BY NhanVien.MaNV)
end
SELECT *
FROM NhanVien
WHERE SoNguoiThan>#SNT
end
GO
Then I get the error :
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 12
Invalid column name 'SoNguoiThan'.
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 15
Invalid column name 'SoNguoiThan'.
Who can help me?
Thanks!
When the stored proc is parsed during CREATE the column does not exist so you get an error.
Running the internal code line by line works because they are separate. The 2nd batch (UPDATE) runs because the column exists.
The only way around this would be to use dynamic SQL for the update and select so it's not parsed until EXECUTE time (not CREATE time like now).
However, this is something I really would not do: DDL and DML in the same bit of code
I ran into this same issue and found that in addition to using dynamic sql I could solve it by cross joining to a temp table that had only one row. That caused the script compiler to not try to resolve the renamed column at compile time. Below is an example of what I did to solve the issue without using dynamic SQL
select '1' as SomeText into #dummytable
update q set q.ValueTXT = convert(varchar(255), q.ValueTXTTMP) from [dbo].[SomeImportantTable] q cross join #dummytable p