2016-04-29 63 views
0

我想要在插入內部運行的select中獲得一個變量的分配。在插入內部的選擇中分配變量

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)); 

從本質上講,我需要使用同一個變量兩次,但分配獲取與

Incorrect syntax near '='. 

我試圖改變分配語法標記,但它並沒有幫助。 我需要的Guids是一樣的。 是否可以這樣做?

回答

1

您可以選擇每行的NEWID()值事前,然後將其轉化每列上INSERTCTE做到這一點:

;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