【问题标题】:SQL - Insert into statement with subquery, then update statementSQL - 插入带有子查询的语句,然后更新语句
【发布时间】:2016-04-11 06:56:19
【问题描述】:

我一直在为一条 SQL 语句苦苦挣扎,但我似乎无法解决这个问题。

我想使用SELECT 子查询在表A 中插入一条新记录。完成后,我想更新表 B 中的记录。

这是我尝试过的(虚拟 SQL,看起来很像):

INSERT INTO [A] (ID, Expiration, Type) 
VALUES ({some-id}, (
    SELECT [B].[Expiration], [B].[Type] FROM [B] 
    WHERE [B].ID = {other-id}))

运行语句时,出现以下错误:

不使用EXISTS引入子查询时,选择列表中只能指定一个表达式

我不太确定错误存在于哪里,但我怀疑这与我在select 中的where 子句有关

编辑 此查询在 .net 解决方案中运行。我有这样的查询设置:

string insertStatement = "INSERT INTO [A] (ID, Expiration, Type) "
    + "VALUES (@someId, (SELECT [B].[Expiration], [B].[Type] "
    + "WHERE [B].ID = @otherId))";

command.CommandText = insertStatement;
command.AddParameter("@someId", someId);
command.AddParameter("@otherId", otherId);
command.ExecuteNonQuery();

【问题讨论】:

  • 你可以使用临时表的概念,然后将临时表插入[A]。

标签: c# sql .net sql-server


【解决方案1】:

试试这个

INSERT INTO [A] (ID, Expiration, Type)
    SELECT {some-id},[B].[Expiration], [B].[Type] FROM [B] 
    WHERE [B].ID = {other-id}

【讨论】:

  • {some-id} 不是表[B] 的一部分,所以这不会给我带来另一个问题吗?
  • 好吧,这似乎可行。已标记为答案,谢谢!
【解决方案2】:

将您的 @someId 变量移动到 Select 查询内。

试试这个

string insertStatement = "INSERT INTO [A] (ID, Expiration, Type) "
    + "(SELECT @someId, [B].[Expiration], [B].[Type] "
    + "WHERE [B].ID = @otherId)";

command.CommandText = insertStatement;
command.AddParameter("@someId", someId);
command.AddParameter("@otherId", otherId);
command.ExecuteNonQuery();

【讨论】:

  • 似乎也有效。赞成。欣赏答案。谢谢
【解决方案3】:

试试这个..

INSERT INTO A(ID,Expiration,Type)
SELECT @SOME_ID,[B].[Expiration], [B].[Type]
FROM [B]
WHERE [B].ID = {other-id}

它应该适合你..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多