【发布时间】: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