Hi!
Imagine this SQL statement:
Code Snippet
INSERT INTO B SELECT * FROM AIf one of the insert fails ... don't continue, the statement fail. For example if any field in A violate a constraint in B, the statement fails.
I want that the statement continue if errors occurs, if i lost a number of rows don't matter ... but if i can save or log this row will be great too !!
Is posible? Any way to do it?
Regards.
Make two statements, by adding a WHERE clause, you can verify the CONSTRAINT and add rows ONLY if the CONSTRAINT passes. Then in the second statement, in the WHERE clause, get the rows that do not pass.
FOR illustration:
Code Snippet
SET NOCOUNT ON
DECLARE @.MyTable table
( RowID int IDENTITY,
Name varchar(20) PRIMARY KEY
)
INSERT INTO @.MyTable VALUES ( 'Bill' )
DECLARE @.MyOtherTable table
( RowID int IDENTITY,
Name varchar(20)
)
DECLARE @.Failures table
( RowID int,
Name varchar(20)
)
INSERT INTO @.MyOtherTable VALUES ( 'Bill' )
INSERT INTO @.MyOtherTable VALUES ( 'Mary' )
INSERT INTO @.MyOtherTable VALUES ( 'Omar' )
-- First, isolate the CONSTRAINT Failures
INSERT INTO @.Failures
SELECT
t.RowID,
t.Name
FROM @.MyOtherTable t
JOIN @.MyTable m
ON m.Name = t.Name
-- Insert the rows that pass the CONSTRAINT test
INSERT INTO @.MyTable ( Name )
SELECT t.Name
FROM @.MyOtherTable t
JOIN @.MyTable m
ON m.Name <> t.Name
SELECT *
FROM @.MyTable
RowID Name
-- --
1 Bill
2 Mary
3 Omar
SELECT *
FROM @.Failures
RowID Name
-- --
1 Bill
Thanks for your reply.
I will write my question in another way. What I want is if I can change the SQL/Server constraint behaviour when a error is thrown. I know that I can do the insert with a "WHERE" clause. But it some cases is useful to perform your own behaviour when the table has a lot of fields and a lot of rows and you are using a INSERT ... SELECT ... clause. There is some utility (NOTIFICATION, TRIGGERS) that help to do this in a speedy way?
Regards.
|||A CONSTRAINT failure occurs BEFORE the data is inserted into the table -so a AFTER INSERT TRIGGER would not work.
You could create a BEFORE INSERT TRIGGER, but then you would STILL have to use the two step process I demonstrated in my earlier post. And there may be increased locking and blocking behavior as a result of using a TRIGGER.
Bottom line is that the CONSTRAINT prevents the data from getting into the table. Without the data getting to the table, there is little to offer in the form of Notifications, etc., and you are also, pardon the ironic pun, constrained in the ability to use a TRIGGER.
|||OK! Thanks.
Regards.
No comments:
Post a Comment