I do some validations and checks in SQL Server triggers, but I couldn't manage to get a custom select statement from a trigger. I need to get it into a temp table or into some variables, how to do that?
Table structure:
create table Orders
(
ID int identity(1,1),
OrderNo nvarchar(50),
Product nvarchar(100),
Quantity int
)
My trigger:
create trigger [dbo].[OrderInsertTrigger]
on [dbo].[Orders]
instead of insert
as
begin
set nocount on;
-- Some Checks here for validation.. some codes..
select 1 as result, 'insert is successful' as message return
end
Insert query to test;
insert into Orders (OrderNo, Product, Quantity)
select 123, 'ice cream', 100
I tried sub brackets (just guessing to capture trigger output) but did not work;
Declare @temp table(bit result, msg nvarchar(200))
insert into @temp
from
(insert into Orders(OrderNo,Product,Quantity) select 123, ''ice cream'', 100')
as t
I tried something dynamic SQL but did not work;
Declare @temp table(bit result, msg nvarchar(200))
insert into @temp Exec('insert into Orders(OrderNo,Product,Quantity) select 123, ''ice cream'', 100')
What is the way to capture that custom select statement from the trigger? or is it possible?
EDIT
My goal is actually, I want to do some validations before the CRUD operations to prevent SQL errors like field nullable check, foreign key check, value range check or some custom check according to what customer needs. I want to reflect my custom response to the client from SQL Server (maybe from trigger or ???)
So my question, how to make audits, validations in a efficient way for too many SQL Server tables in a static or dynamic way?