0

I want to execute this query :

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

but the following error occurs :

Subqueries are not allowed in this context. Only scalar expressions are allowed.

4 Answers 4

4

Try

INSERT INTO [Order] (FactorId, ProductId, Entity) 
SELECT Top 1 FactorId, @ProductId, @Entity FROM Factor WHERE UserId = @UserId AND Status = -1
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I executed this query, but the following error occurs: The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
0

try with this

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

Note : insert query with select wont allow VALUES keyword :) .

Comments

0

if you have other columns involved, avoid the TOP 1 altogether and consider something like this...

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)

This concept also works if you have a sort-order column or any other unique column

1 Comment

There are other better answers. This is more complicated and has the risk of inserting multiples when max(timestamp) is not unique

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.