2

I'm trying to insert data from one table into a table that has a two-column key. The source table does not share the destination's keys. Both key columns in the destination are varchars.

I have an insert statement:

INSERT INTO Table1 (Invoice, DetailLine, SomeData1, SomeData2) 
SELECT ('1'+RIGHT('00000000000000' + CONVERT(varchar, DatePart(ns,SYSDATETIME()), 14), 0, 'STARTING_VALUE_1407', [ActualValue] 
FROM Table2;

When I execute the above, my milliseconds for my DateTime2 object are all the same, as if it's only evaluating that value once. This is preventing me from using this as a temporary unique key. Is it possible to use SYSDATETIME(), or any other date function, in a SELECT statement and have the value reevaluated for each row? If not, is there a way to generate a unique value when doing an INSERT INTO SELECT when selecting data that doesn't normally share the destination table's key?

4

2 回答 2

6

SYSDATETIME()函数在您的查询中被评估一次,因为它被认为是一个运行时常量。

您可以尝试窗口功能,例如ROW_NUMBER()

INSERT INTO table1 
         (invoice, 
          detailline, 
          somedata1, 
          somedata2) 
SELECT ROW_NUMBER() 
         OVER (ORDER BY actualvalue), 
       0, 
       'STARTING_VALUE_1407', 
       [actualvalue] 
FROM   table2; 
于 2014-09-23T14:45:26.157 回答
1

我不确定您是否需要绑定到毫秒,或者同一行中的值是否需要相同,但可以使用以下方法来获得唯一性:

SELECT NEWID() AS GuidNo1, 
       NEWID() AS GuidNo2 

或者

SELECT CAST(RAND() * 1000000 AS INT) AS [RandomNumber1], 
       CAST(RAND() * 1000000 AS INT) AS [RandomNumber2] 
于 2014-09-23T14:55:02.217 回答