SQL Server插入查询问题

时间:2009-09-26 14:34:47

标签: sql sql-server tsql insert

我想执行此查询:

INSERT INTO [Order] (FactorId, ProductId, Entity) 
VALUES((SELECT Top 1 FactorId FROM Factor WHERE UserId = @UserId AND Status = -1), @ProductId, @Entity)

但发生以下错误:

  

此处不允许使用子查询   上下文。只有标量表达式   允许的。

4 个答案:

答案 0 :(得分:4)

尝试

INSERT INTO [Order] (FactorId, ProductId, Entity) 
SELECT Top 1 FactorId, @ProductId, @Entity FROM Factor WHERE UserId = @UserId AND Status = -1

答案 1 :(得分:0)

INSERT INTO [Order] (FactorId, ProductId, Entity) 
SELECT (select Top 1 FactorId FROM Factor WHERE UserId = @UserId AND Status = -1), 
@ProductId, @Entity

答案 2 :(得分:0)

试试这个

INSERT INTO [Order] (FactorId, ProductId, Entity) 
(SELECT Top 1 FactorId, @ProductId, @Entity FROM Factor 
WHERE UserId = @UserId AND Status = -1)

注意:使用select不允许 VALUES 关键字:)插入查询。

答案 3 :(得分:0)

如果您涉及其他专栏,请完全避开TOP 1,并考虑这样的事情......

INSERT INTO [Order] (FactorId, ProductId, Entity) 
SELECT FactorId, @ProductId, @Entity FROM Factor 
WHERE UserId = @UserId 
  AND Status = -1
  and timestamp = (select max(timestamp) from Factor where UserId = @UserId AND Status = -1)

如果您有排序顺序列或任何其他唯一列

,此概念也适用