0

I need to add multirows at the same time in my sql server Table using this code

declare @idproduct int
declare @idfile int

set @idproduct = (select id from Products where name = 'DR-8416')
set @idfile = (select id from Files where filename like '%8416%')

insert into ProductsFiles(idproducts, idfile) values (@idproduct, @idfile)

that @idfile is an array with many values; when I try to add I recied this error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

How Can I solve this Problem ?

7
  • What you have there doesn't make sense as it stands. What are you expecting to INSERT here? A cartesian product of every id from Files and Products (that meet the requisite of the WHERE)? Commented Jun 3, 2019 at 8:04
  • Use While loop to fetch each record and insert to your target table Commented Jun 3, 2019 at 8:05
  • @Sreenu131 no, don't use a WHILE loop, that is awfully slow. SQL Server excels as Set Based methods, not iterative ones. I suggest against using that methodology Farshad Razaghi. Commented Jun 3, 2019 at 8:06
  • @Larnu I have some products that has many files; an a table that connect them together. some files are same for some products Commented Jun 3, 2019 at 8:06
  • 2
    So what links Files and Products? Don't forget, we can't see your data, and we don't have any samples or expected results. Best I can suggest at the moment is you want INSERT INTO...SELECT syntax. Commented Jun 3, 2019 at 8:07

1 Answer 1

1

Best I can guess is what you are after is:

INSERT INTO ProductsFiles (idproducts,
                           idfile)
SELECT P.id,
       F.id
FROM Products AS P
     CROSS JOIN Files AS F
WHERE P.[name] = 'DR-8416'
  AND F.[filename] LIKE '%8416%';

Note I have used as CROSS JOIN, as your question suggests there is no relationship between Products and Files. If there is change the CROSS JOIN to an INNER JOIN and add the relevant ON clause. If you don't know about JOIN syntax I suggest looking it up, and learning it. JOIN syntax is one of the fundamentals for SQL and you will not get far without learning it. You will learn far more by taking the time to read up about it than me giving you an answer and trying to explain the basics.

Sign up to request clarification or add additional context in comments.

Comments

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.