Reputation: 201
Is it possible to insert into a table based on a count condition (using just 1 statement)? I want to do something like this:
insert into [table] (...) values (...) if select count(*) from [table] < 5
(insert into the table only if it has less than 5 entries)
Upvotes: 1
Views: 2176
Reputation: 1046
In my opinion, above solutions does not include group by command. It leads to error. I suppose that you want to insert all rows which has count less than 5, but grouped by some column. Please correct me if I am wrong.
For example: we have table "table" with rows "ID" and "name", and we want to select and insert only those rows which name is not repeating more than 5 times in a table.
select * from table where name in ( select name from table group by name having count(*)<5 )
I would also consider using select into command. Good luck :)
Well, I think that I have just understood your problem, and I think that my answer is not about it. Anyway, I hope that my answer will be helpful for you or someone else.
Upvotes: 0
Reputation: 24219
try something like this:
insert into [table] (#FIELDS#)
select (#VALUES#) from [table]
where (select count(*) from [table]) < 5
FETCH FIRST ROW ONLY
Upvotes: 3
Reputation: 28413
You can try like this
insert into [table] (...) values Select (...) from [table] Where count(*) < 5
Upvotes: 1