0

I'm trying to get the assignment of a variable inside a select which runs inside an insert.

INSERT INTO myTable
            (Value1,Value2,Value3)
            VALUES
            (
            (
                    SELECT 'SomeText' + @MyGuid = lower(convert(varchar(36), newid())) + '"Some more text" />' AS Value1,
                    @MyGuid AS Value2,
                    columnX AS Value3 FROM myOtherTable));

Essentially, I need to use the same variable twice, but the assignment gets flagged with

Incorrect syntax near '='.

I tried changing the assignment syntax, but it did not help. I need the Guids to be the same. Is it possible to do so?

1 Answer 1

1

You can do this with a CTE by selecting the NEWID() value for each row beforehand, then transforming it per column on the INSERT:

;With ToInsert As
(
    Select  lower(convert(varchar(36), newid())) As MyGuid,
            ColumnX As Value3
    From    MyOtherTable
)
Insert  MyTable
        (Value1, Value2, Value3)
Select  'SomeText' + MyGuid + '"Some more text" />' As Value1,
        MyGuid As Value2,
        Value3
From    ToInsert
Sign up to request clarification or add additional context in comments.

Comments

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.