Conditional INSERT

This is a discussion on Conditional INSERT within the MySQL Database forums, part of the Database Forums category; Hello, I'm trying to perform an INSERT .. but only if no rows in the table have a specific field ...


Go Back   Usenet Forums > Database Forums > MySQL Database

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 06-25-2007
evanpeck@gmail.com
 
Posts: n/a
Default Conditional INSERT


Hello,

I'm trying to perform an INSERT .. but only if no rows in the table
have a specific field that equals zero.

For example:

Nodes has the fields NodeID and ParentNodeID (there are more than
that, but this is simplified)

NodeID will be unique no matter what, since it is incremental.

I want to
INSERT INTO Nodes
VALUES(NULL, 0)

only if
// There are no Nodes that have a ParentNodeID of 0
SELECT COUNT(NodeID)
FROM Nodes
WHERE ParentNodeID = 0 is less than 1

Thank you

Reply With Quote
  #2 (permalink)  
Old 06-25-2007
ZeldorBlat
 
Posts: n/a
Default Re: Conditional INSERT

On Jun 25, 2:19 pm, evanp...@gmail.com wrote:
> Hello,
>
> I'm trying to perform an INSERT .. but only if no rows in the table
> have a specific field that equals zero.
>
> For example:
>
> Nodes has the fields NodeID and ParentNodeID (there are more than
> that, but this is simplified)
>
> NodeID will be unique no matter what, since it is incremental.
>
> I want to
> INSERT INTO Nodes
> VALUES(NULL, 0)
>
> only if
> // There are no Nodes that have a ParentNodeID of 0
> SELECT COUNT(NodeID)
> FROM Nodes
> WHERE ParentNodeID = 0 is less than 1
>
> Thank you


if not exists (select 1 from nodes where ParentNodeID = 0) begin
insert into Nodes
values(null, 0);
end if;

Reply With Quote
  #3 (permalink)  
Old 06-25-2007
evanpeck@gmail.com
 
Posts: n/a
Default Re: Conditional INSERT

Unfortunately, that doesn't seem to be working for me.

I get a sytax error near

"if not exists (select 1 from nodes where ParentNodeID = 0) be"

Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT +1. The time now is 05:23 AM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.0.0