【问题标题】:SQL Server Insert Into SelectSQL Server 插入选择
【发布时间】:2014-10-05 18:32:21
【问题描述】:

我在尝试INSERT一列中的一个值,结果一个SELECT这句话效果很好:

insert into tempdepa (Trabajadores) 
   (select count (DepartmentName) 
    from DimEmployee 
    where DepartmentName = @d)

但我想将 SELECT 插入特定列:

insert into tempdepa (Trabajadores) 
   (select count (DepartmentName) 
    from DimEmployee 
    where DepartmentName = @d) 

其中 id = @cont

最后一个where id = @cont 来自第一个表(tempdepa)...我试过了

insert into tempdepa (Trabajadores where id = @cont) 
    (select count (DepartmentName) 
     from DimEmployee 
     where DepartmentName = @d)

但它不起作用。我该怎么做?

【问题讨论】:

  • 不清楚,但我认为你需要一个 JOIN。
  • 如果您想更改现有行的值,您可能需要使用UPDATE 而不是INSERTINSERT 不能用 WHERE 子句“参数化” - 它只是插入一个新行。

标签: sql sql-server select insert


【解决方案1】:

如果你需要插入新行,你需要这样做:

insert into tempdepa (Trabajadores, id)
select count(DepartmentName), @cont
from DimEmployee where DepartmentName = @d

如果你想更新现有的:

update tempdepa
set Trabajadores=(select count (DepartmentName) from DimEmployee where DepartmentName = @d)
where id = @cont

【讨论】:

  • Lashane 明白了。只有在创建全新行时才使用 INSERT。如果要更改现有行上的字段,则需要使用 UPDATE。
  • 哇,谢谢大家!你是对的@LASHANE 我没有意识到我正在插入新行......但我需要更新:D 谢谢!!!!!!!!!!!!
猜你喜欢
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多