简体   繁体   中英

How to trigger before INSERT statement in stored procedure in SQL Server 2005?

I read this Help with SQL Server Trigger to truncate bad data before insert but not solve my issue when is about stored procedure.

update

Because of my issue Why cannot create global temporary table or truncate it when call a stored procedure from C# code? when truncate table from stored procedure when it is called from C# code.

end update

The stored procedure is

ALTER PROCEDURE [dbo].[aProcedure]
  @val1 VARCHAR(255),
  @val2 VARCHAR(255),
  ...
AS 
BEGIN
   SELECT @sql = '//Do SELECT statement'

    INSERT INTO dbo.MyTable(....)

    SELECT @paramList = ' /*list of parameters*/';

    EXEC sp_executesql @sql, @paramList, ... parameters
END

And the trigger I used (I'm beginner in SQL)

CREATE TRIGGER MyTrigger ON dbo.MyTable
FOR INSERT
AS
BEGIN
    TRUNCATE dbo.MyTable
END

How do trigger, when from stored procedure the values are inserted into dbo.MyTable , which truncate my table first and after that make INSERT operation ?

I read the documentation from MSDN and CodeProject .

Thank you

In the stored procedure itself truncate the table. No need to write a trigger . Trigger will slow down your process

ALTER PROCEDURE [dbo].[aProcedure]
  @val1 VARCHAR(255),
  @val2 VARCHAR(255),
  ...
AS 
BEGIN
   SELECT @sql = '//Do SELECT statement'

     TRUNCATE table  dbo.MyTable -- < add truncate here
    INSERT INTO dbo.MyTable(....)

    SELECT @paramList = ' /*list of parameters*/';

    EXEC sp_executesql @sql, @paramList, ... parameters
END
CREATE TRIGGER MyTrigger ON dbo.MyTable
AFTER INSERT
AS
BEGIN
    TRUNCATE dbo.MyTable
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM