2

I have an instead of trigger. I have a value in a variable.

I would like to insert the value into one of the columns and use the fields from inserted. This is what I am trying to accomplish:

declare @someLocalVariable varchar(9)

set @someLocalVariable = dbo.someLocalUDF()

INSERT myTable (field1, field2, field3)
VALUES (@someLocalVariable, (select field2, field3 from inserted))
0

1 Answer 1

7
INSERT INTO myTable (
    field1,
    field2,
    field3
) SELECT
    @someLocalVariable,
    field2,
    field3
FROM
    INSERTED

Just remember that if this was triggered by a batch insert (i.e. INSERTED has more than one record), all records will also be inserted into the target table.

(Which is exactly what it should do IMHO, but for some reason people usually forget about that.)

Edit

The OP has forgotten to say what his question was really about: generating unique primary key values. So, in that case, one way of doing that would be something like this:

CREATE TRIGGER
    dbo.InsteadOfInsertMyTable
    ON MyTable
    INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO myTable (
        primaryKeyField,
        field2,
        field3
    ) SELECT
        dbo.someUniqueValueGeneratorUDF(),
        field2,
        field3
    FROM
        INSERTED
END
GO
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Not sure why the OP doesn't just use a default for this though.
my udf is incrementing a string primary key. so you are correct it will not work for bulk insert. Is there a way to update INSERTED with the udf values and then insert all of inserted?
@tim: ah, got it. Not a problem - just call the function directly from the insert statement. I'll edit my answer.
thanks rsenna. Yes I was trying to post a fragment of my overall problem. I will mark as answered and repost with my overall issue. But thanks for answering my questions and pointing out the issues with my approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.