Insert into a table only if count is less than 'n'

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • raghulvarma
    New Member
    • Oct 2007
    • 90

    Insert into a table only if count is less than 'n'

    I need to insert the record in the database only if the count is less than 'n'.
    ie if i need to enter a name first i need to find the count of name if it is less than 2 then isert the name and if it is more than 2 then it should not be entered,
    i tried but it does not work where did i go wrong??

    insert into tablename values('aaa') where count(*)columnn ame <=2

    I think where could not be used with aggregate functions instead of that what has to be put?
  • yumbelie
    New Member
    • Dec 2007
    • 9

    #2
    Originally posted by raghulvarma
    I need to insert the record in the database only if the count is less than 'n'.
    ie if i need to enter a name first i need to find the count of name if it is less than 2 then isert the name and if it is more than 2 then it should not be entered,
    i tried but it does not work where did i go wrong??

    insert into tablename values('aaa') where count(*)columnn ame <=2

    I think where could not be used with aggregate functions instead of that what has to be put?
    Look up on Google the IF and CASE statements. In your case you would need to do something like:

    Code:
    IF (SELECT COUNT(*) FROM [tablename]) <= 2 
          INSERT INTO [tablename] ([column]) VALUES 'aaa'

    Comment

    Working...