Is there any way to programmatically detect the current value(s) of the IDENTITY_INSERT property, specifically (a) whether it's ON or OFF, and/or (b) if it's ON which table it's on for?
I have a table with an INSTEAD OF INSERT trigger which does a data check prior to insertion. The table has existing data. I'm trying to add the IDENTITY property to one of the columns in the PK so that going forward, the PK value is automatically generated on new rows. Unfortunately, the INSERT in the trigger only works if IDENTITY_INSERT is off. If IDENTITY_INSERT myTable is ON, the INSERT statement in the trigger fails because the identiy column is not coded in it.
I tried putting the INSERT in a TRY...CATCH block, testing for error 545 in the CATCH and issuing a second INSERT with the PK column coded in it, but once you hit the CATCH block in a trigger SQL Server deems the entire transaction as "failed", and you can only roll it back (error 3930).
CREATE TRIGGER myTable_tIiof
ON myTable INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
IF (EXISTS (SELECT TOP 1 i1.col2 FROM inserted i1
WHERE (EXISTS (SELECT TOP 1 r1.col1
FROM myTable r1
WHERE i1.col2= r1.col2
AND UPPER(i1.col3) = UPPER(r1.col3)) ))) BEGIN
PRINT 'INSERT failed - violation of duplicate col2 and col3 restriction';
END ELSE
BEGIN TRY
INSERT INTO myTable (col2, col3, col4)
SELECT i.col2, i.col3, i.col4 FROM inserted i
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 545 BEGIN -- IDENTITY_INSERT is on:
BEGIN TRY
INSERT INTO myTable (col1, col2, col3, col4)
SELECT i.col1, i.col2, i.col3, i.col4 FROM inserted i
END TRY
BEGIN CATCH -- Some other error occurred after second INSERT attempt:
SELECT ERROR_NUMBER() AS ErrorNumber;
IF @@TRANCOUNT > 0 ROLLBACK;
END CATCH
END ELSE BEGIN --
SELECT ERROR_NUMBER() AS ErrorNumber;
IF @@TRANCOUNT > 0 ROLLBACK;
END
END CATCH
END
IDEALLY, I want to do the following:
CREATE TRIGGER myTable_tIiof
ON myTable INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
IF (EXISTS (SELECT TOP 1 i1.col2 FROM inserted i1
WHERE (EXISTS (SELECT TOP 1 r1.col1
FROM myTable r1
WHERE i1.col2= r1.col2
AND UPPER(i1.col3) = UPPER(r1.col3)) ))) BEGIN
PRINT 'INSERT failed - violation of duplicate col2 and col3 restriction';
END ELSE BEGIN
IF MissingFunction1(IsIdentityInsertOn) = true AND MissingFunction2(IdentityInsertObject) = 'myTable' BEGIN
INSERT INTO myTable (col1, col2, col3, col4)
SELECT i.col1, i.col2, i.col3, i.col4 FROM inserted i
END ELSE BEGIN
INSERT INTO myTable (col2, col3, col4)
SELECT i.col2, i.col3, i.col4 FROM inserted i
END
END
Do MissingFunction1 and/or MissingFunction2 exist? If so, what are they called?
(And if they don't exist, why don't they exist?)
Thanks in advance... Bryan