使用带有特定数据的select语句插入值

时间:2016-09-18 16:03:01

标签: sql sql-server

我正在尝试将数据插入到特定的表中。该表为客户数据创建了一个标识密钥。

例如:

我有一个名为table3的表,其中包含ID,GroupID,InsertDate,UpdateDate,ProfileID等列

我有一个选择查询

   Insert into table 
    (GroupID, InsertDate, ProfileID)
    with resultsOne AS (select GroupID, GetDate() as InsertDate from table1 t1 
where GroupID ="1007")
    , resultsTwo AS (select Distinct ProfileID from table2 t2)
        select t1.*, t2.* from resultsOne, resultsTwo

我在个人资料表中总共有14,000条记录。基于此我想插入14,000条记录,但它插入800,000条记录。那么我怎样才能为14,000条记录生成一个ID?

表格看起来像这样。

+-----------+-----------+--------------------------+-------------------+-------------------+
+    ID     +  GroupID  +    InsertedDare          +    UpdatedDate    +     ProfileID     +
+-----------+-----------+--------------------------+-------------------+-------------------+
+     1     +   1007    +  2016-09-18 16:33:33.967 +        NULL       +     67885612      +
+-----------+-----------+--------------------------+-------------------+-------------------+
+     2     +   1007    +  2016-09-18 16:34:33.967 +        NULL       +     67885613      +
+-----------+-----------+--------------------------+-------------------+-------------------+
+     3     +   1007    +  2016-09-18 16:35:33.967 +        NULL       +     67885617      +
+-----------+-----------+--------------------------+-------------------+-------------------+
+     4     +   1007    +  2016-09-18 16:36:33.967 +        NULL       +     67885618      +
+-----------+-----------+--------------------------+-------------------+-------------------+

要更新的ID来自table1,而ProfileID来自table2。

1 个答案:

答案 0 :(得分:0)

使用CTE语法插入时应该像这样

;with cte as
(
select ...
)
Insert into tablename(col1,..)
Select col1,.. from cte

这是正确的方法

;WITH resultsone 
     AS (SELECT Distinct groupid, 
                Getdate() AS InsertDate 
         FROM   table1 t1), 
     resultstwo 
     AS (SELECT DISTINCT profileid 
         FROM   table2 t2) 
INSERT INTO table 
            (groupid, 
             insertdate, 
             profileid) 
SELECT t1.groupid, 
       t1.InsertDate 
       t2.profileid 
FROM   resultsone t1 
       CROSS JOIN resultstwo t2 

很少有事情需要考虑

  • 始终在Insert&中添加列列表插入记录时Select
  • 使用Cross Join获取两个表的 Cartesian 产品,而不是旧的stlye逗号分隔连接
相关问题