If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Var in Subquery Problem

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-17-11, 17:26
xX_QueAnw_Xx xX_QueAnw_Xx is offline
Registered User
 
Join Date: Mar 2011
Posts: 1
Var in Subquery Problem

Hey,
I try to write an trigger which generates an ID for me. Unfortunately it throws an error. I think it's because of the var in the subquery

here my sourcecode:

Code:
DELIMITER #;
CREATE TRIGGER bi_user_id
BEFORE INSERT ON user
FOR EACH ROW

BEGIN
DECLARE i,ie INTEGER DEFAULT 0;
DECLARE leer CHAR(16) DEFAULT 'True';

SELECT count(*) INTO i FROM user;
SELECT ID INTO ie FROM user WHERE ID=(SELECT i);
IF ie>0 THEN
SELECT * FROM user;
ELSE
SELECT leer;
END#
The actions that are taken in the IF ELSE part are just test because I dont have an Backup of this Table and I dont want anything to come wrong.

sincerelly.
Reply With Quote
  #2 (permalink)  
Old 03-18-11, 03:40
it-iss.com it-iss.com is offline
Registered User
 
Join Date: Sep 2009
Location: San Sebastian, Spain
Posts: 623
Hi,

Firstly, a trigger is something that runs in the background as data is added, deleted or updated in a table. A trigger should never return any rows. This is just not permitted. I will assume that you are looking to create a stored procedure. There are several things that you should look closely at with this procedure:
  • From a functional perspective, if the ID's are consecutive without any gaps then this will work. Have you considered looking for the MAX(ID) instead?
  • There is no exception handling in the event that the query does not find a record.

I would propose something as follows:

Code:
CREATE PROCEDURE spUser()
BEGIN
  DECLARE leer CHAR(16) DEFAULT 'True';

  DECLARE ie INT;

  DECLARE CONTINUE HANDLER
  FOR NOT FOUND
    SET leer = 'True';

  SELECT id
  INTO   ie
  FROM   user
  WHERE  id = (SELECT Max(id)
               FROM   user);

  IF ie > 0 THEN
    SELECT *
    FROM   user;
  ELSE
    SELECT leer;
  END IF;
END;
__________________
Ronan Cashell
Senior Oracle/MySQL DBA
http://www.it-iss.com
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
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

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