【问题标题】:t sql select into existing table new columnt sql 选择到现有表中的新列
【发布时间】:2013-05-08 09:04:17
【问题描述】:

您好,我有一个临时表 (#temptable1),我想从另一个临时表 (#temptable2) 中添加一列,我的查询如下:

select 
Customer
,CustName
,KeyAccountGroups
,sum(Weeksales) as Weeksales
into #temptable1
group by Customer
,CustName
,KeyAccountGroups


select
SUM(QtyInvoiced) as MonthTot
,Customer
into #temptalbe2
from SalesSum
where InvoiceDate between @dtMonthStart and @dtMonthEnd
group by Customer


INSERT INTO #temptable1
SELECT MonthTot FROM #temptable2
where #temptable1.Customer = #temptable2.Customer

我得到以下信息:列名或提供的值的数量与表定义不匹配。

【问题讨论】:

标签: tsql


【解决方案1】:

INSERT 语句中,您不能引用要插入的表。插入是在要创建新行的假设下工作的。这意味着没有可以引用的现有行。

您正在寻找的功能由UPDATE 语句提供:

UPDATE t1
SET MonthTot = t2.MonthTot 
FROM #temptable1 t1
JOIN #temptable2 t2
ON t1.Customer = t2.Customer;

但请注意,此逻辑要求 t2 中的 Customer 列是唯一的。如果您在该表中有重复的值,则查询似乎运行良好,但您最终会得到随机变化的结果。

有关如何在UPDATEDELETE 中组合两个表的更多详细信息,请查看我的A Join A Day - UPDATE & DELETE 帖子。

【讨论】:

    【解决方案2】:

    如果我理解正确,您想做两件事。 1:更改表 #temptable1 并添加一个新列。 2:用#temptable2的值填充该列

    ALTER #temptable1 ADD COLUMN MothTot DATETIME
    
    UPDATE #temptable1 SET MothTot = (
        SELECT MonthTot 
        FROM #temptable2
        WHERE #temptable2.Customer = #temptable1.Customer)
    

    【讨论】:

    • 您好,我更新了 #temptable1 以使所有 NULL 值都为零,但现在我得到了 Invalid column name 'Monthtot'。
    • @wilest 用你的#temptable1 描述更新你的问题。我假设您的 #temptable1 有一个 Monthtot 列。
    • 不,我想在 temptable2 中添加一个新列到 temptable1,我会更新我的问题
    • @wilest 好的,我想我现在明白你的问题了,我会更新我的答案。给我几分钟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多