Is there any way in mysql with witch I can take the results of the first query as parameter for the second query in the same procedure?
Yes you can you just need to declare the variable and set the value according to the result of your first query:
DELIMITER //
CREATE PROCEDURE myProc()
BEGIN
DECLARE productname VARCHAR(100);
SET productname = (SELECT product FROM products WHERE product_id = 1);
SELECT * FROM otherproducttable WHERE product = productname;
END //
DELIMITER ;
or
DELIMITER //
CREATE PROCEDURE myProc()
BEGIN
DECLARE productname VARCHAR(100);
SELECT product INTO productname FROM products WHERE product_id = 1;
SELECT * FROM otherproducttable WHERE product = productname;
END //
DELIMITER ;
Related
I'm trying to generate URL in SQL database using already assigned auto_incremented ID
When a new form is submitted then SQL automatically generates and unique lens_id for me. How can I automatically add it there in this lens_url? (Picture below)
You can do this by creating a trigger on your table. Trigger is as follows,
DELIMITER $$
CREATE TRIGGER `UpdateLensURL` BEFORE INSERT ON `your_table_name`
FOR EACH ROW BEGIN
SET NEW.lens_url= CONCAT('localhost:8888/lensview/post.php?id=', (
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'your_table_name'
));
END;
$$
DELIMITER ;
There are two options here:
1) Use a stored procedure (which will require code changes for anywhere that inserts rows)
2) Use a trigger and insert as normal - something like below should do the trick:
DELIMITER //
CREATE TRIGGER my_awesome_trigger
BEFORE INSERT
ON your_table_name
FOR EACH ROW
BEGIN
DECLARE next_id int default 0;
SELECT auto_increment INTO next_id
FROM information_schema.tables
WHERE table_name = 'your_table_name'
AND table_schema = DATABASE();
SET NEW.lens_url = CONCAT('localhost:8888/.../', next_id);
END; //
DELIMITER ;
Try something like this
$qry1="insert into tablename(lens_name,lens_url,lens_category,lens_author,lens_discription,lens_repert)values('A','B','C','D','E','F')";// your query to insert data to table
mysqli_query($con,$qry1); // run query
$last_insertid=mysqli_insert_id($con); // save last insetred ID
$url="localhost:8888/lenseview/post.php?id=".$last_insertid; //prepare url
$qry2="upadte tablename set lens_url=$url where lens_id=$last_insertid"; //update query
mysqli_query($con,$qry2); // run your query to update url
I think easiest option would be this
$Last_Lens_IdQ = mysqli_query($conn, "SELECT `lens_id` FROM `table` ORDER BY `lens_id` DESC LIMIT 1");
$Last_LensId = mysqli_fetch_array($Last_Lens_IdQ);
$x = $Last_Lens[0]++;
$LensUrl = "localhost:8888/lenseview/post.php?id=".$x;
Then insert the field and use $LensUrl When inserting the lens url column
I use Wordpress with a database. My problem is that I want to retrieve the inserted ID when using wpdb-> insert. I want to clarify that I increment the ID using a database trigger because my table is a relative entity. I was thinking of creating a procedure that I would call after my insertion.
My trigger
BEGIN
DECLARE num INTEGER;
IF NEW.id IS NULL THEN
SET num =
(
SELECT MAX(id) + 1
FROM ab_autreFrais
WHERE idDevis = NEW.idDevis
);
SET NEW.id = num;
ELSEIF NEW.id = 0 THEN
SET num =
(
SELECT MAX(id) + 1
FROM ab_autreFrais
WHERE idDevis = NEW.idDevis
);
SET NEW.id = num;
END IF;
END
There is the LAST_INSERT_ID() function that you can use instead of the trigger. Also you can get this value through an output parameter of a stored procrdure.
Or you could use auxiliary table or a global variable to put id value from the trigger. For example:
...
SET NEW.id = num;
UPDATE `SysData` SET `LastID` = num;
...
#Alexander
UPDATE ``SysData`` SET ``LastID`` = num; Does not work on MySQL SysData is not exist. I used SET SESSION last_insert_id = num in sql on phpmyadmin it work but with wpdb when i call last_insert_id() it return 0
I have written a stored procedure in mysql which will create a TEMPORARY TABLE, I want to access the data of TEMPORARY TABLE using Codeigniter.But when I call "$this->db->query()" it returns empty data.
$data=array();
$call_procedure = "CALL sp_Stock()";
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);
I have changed my way to show the data. And I do changes it on stored procedure.
DELIMITER $$
CREATE PROCEDURE sp_Stock()
BEGIN
DECLARE cursor_finish INTEGER DEFAULT 0;
DECLARE m_numofpurchaseBag DECIMAL(10,2)DEFAULT 0;
DECLARE m_purchasedKg DECIMAL(10,2)DEFAULT 0;
DECLARE m_purBagDtlId INTEGER DEFAULT 0;
DECLARE stockCursor CURSOR FOR
SELECT purchase_bag_details.`actual_bags`,
(purchase_bag_details.`net`*purchase_bag_details.`actual_bags`) AS PurchasedKg,
purchase_bag_details.`id` AS PurchaseBagDtlId
FROM
purchase_invoice_detail
INNER JOIN
purchase_bag_details
ON purchase_invoice_detail.`id`= purchase_bag_details.`purchasedtlid`
INNER JOIN
`do_to_transporter`
ON purchase_invoice_detail.`id` = do_to_transporter.`purchase_inv_dtlid`
WHERE purchase_invoice_detail.`teagroup_master_id`=6
AND purchase_invoice_detail.`id`=1481
AND do_to_transporter.`in_Stock`='Y';
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET cursor_finish = 1;
DROP TEMPORARY TABLE IF EXISTS StockTable;
#temptable creation
CREATE TEMPORARY TABLE IF NOT EXISTS StockTable
(
purchaseBagDtlId INT,
purchasedBag NUMERIC(10,2),
purchasedKg NUMERIC(10,2),
blendedBag NUMERIC(10,2),
blendedKg NUMERIC(10,2),
stockBag NUMERIC(10,2),
stockKg NUMERIC(10,2)
);
#temptable creation
OPEN stockCursor ;
get_stock : LOOP
FETCH stockCursor INTO m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId;
IF cursor_finish = 1 THEN
LEAVE get_stock;
END IF;
/*SELECT m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId; */
/* Blending bag query*/
SET #m_numberofBlndBag:=0;
SET #m_BlndKg:=0;
/* Blend bag*/
SELECT #m_numberofBlndBag:=SUM(blending_details.`number_of_blended_bag`) AS belendedBag INTO #m_numberofBlndBag
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
#Blend Bag
#Blend Kgs
SELECT #m_BlndKg:=SUM(blending_details.`qty_of_bag` * blending_details.`number_of_blended_bag`) AS blendkg INTO #m_BlndKg
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
SET #m_StockBag:=(m_numofpurchaseBag - #m_numberofBlndBag);
SET #m_StockKg:=(m_purchasedKg - #m_BlndKg);
INSERT INTO StockTable
(
purchaseBagDtlId ,
purchasedBag ,
purchasedKg ,
blendedBag ,
blendedKg ,
stockBag ,
stockKg
)VALUES(m_purBagDtlId,m_numofpurchaseBag,m_purchasedKg,#m_numberofBlndBag,#m_BlndKg,#m_StockBag,#m_StockKg);
END LOOP get_stock;
CLOSE stockCursor;
SELECT * FROM StockTable;
#DROP TABLE StockTable;
END$$
DELIMITER ;
#CALL sp_Stock();
Anywhere I am using a temp table I am executing this before the temp table is created:
$this->db->query('DROP TABLE IF EXISTS StockTable');
I seem to remember reading someone having the same problem as you and for some reason you have to execute the above first.
So try:
$data=array();
$call_procedure = "CALL sp_Stock()";
$this->db->query('DROP TABLE IF EXISTS StockTable');
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);
I have a procedure called SELECT_DESCRIPTION that receives an id and returns a Description field I need to show in my page.
Now I want to create a new procedure that having a number of ids coming from a select clause like this:
SELECT id FROM MYTABLE
Can pass it to the SELECT_DESCRIPTION procedure so I can have the same number of descriptions
If I was using php I would be doing something like this:
$sql=”SELECT id FROM MYTABLE”;
$result = mysql_query($sql) //using mysql to make the example faster but TSQL is what I use
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$newSql = "EXEC SELECT_DESCRIPTION #id = '$row[‘id’]'";
//do whatever with $newSql
}
But I need to use a procedure. Is is possible to do it? How can I do it?
Thanks a ton!
So you're wanting to do all of this in TSQL? Something like this would do it:
DECLARE #tmp TABLE (tmpID INT IDENTITY, tblID INT)
DECLARE #RecordCount INT,
#LoopCount INT,
#ID INT
INSERT INTO #tmp SELECT id FROM MYTABLE
SELECT #RecordCount = COUNT(*) FROM #tmp
SET #LoopCount = 1
WHILE #LoopCount <= #RecordCount
BEGIN
SELECT #ID = tblID FROM #tmp WHERE tmpID = #LoopCount
EXEC SELECT_DESCRIPTION #ID
SELECT #LoopCount = #LoopCount + 1
END
The #tmp table has an identity column that insures whatever data you're running the loop on has consecutive row numbers (1, 2, 3, 4, etc).
I am looking to create a function that gets me a random item from a mySQL table, but let's me keep the returned as the "item of the day". In other words, the item that was "the item of the day" yesterday should not be shown again until all other items have been shown as item of the day.
Any suggestions on how to do this in an elegant way?
Thanks
Add a bool column "UsedAsItemOfTheDay" set to false (0). Update to true when item is picked. Exclude already used items from the picking process.
SELECT * FROM `table`
WHERE UsedAsItemOfTheDay = 0
ORDER BY RAND() LIMIT 1;
(Note: this is not the fastest way to return a random row in MySql; it will be slow on huge tables)
See also: quick selection of a random row from a large table in mysql
SELECT <fields> FROM <table> WHERE <some logic to exclude already used> ORDER BY RAND() LIMIT 1 will get you a random row from the table.
Add a column to store whether the item has been used:
ALTER TABLE your_table ADD COLUMN isused BOOL DEFAULT 0;
Get a random item of the day:
SELECT t.*
FROM your_table t
WHERE t.isused = 0
ORDER BY RAND()
LIMIT 1
Now update that record so it can't be used in the future:
UPDATE your_table
SET isused = 1
WHERE id = id_from_select_random_statement
People who "know" SQL will look for declarative solutions and will shun procedural code. Flagging rows is a "smell" for procedural code.
Is the set of Items static (never changes) or stable (rarely changes)? If yes, it would be easier to do a one-off exercise of generating a lookup table of values from now until the end of time, rather than scheduling a proc to running daily to look for unused flags and update the flag for today and clear all flags if all have been used etc.
Create a table of sequential dates between today and a far future date representing the lifetime of your application (you could consider omitting non-business days, of course). Add a column(s) referencing the key in you Items table (ensure you opt for ON DELETE NO ACTION referential action just in case those Items prove not to be static!) Then randomly assign the whole set of Items one per day until each has been used once. Repeat again for the whole set of Items until the table is full. You could easily generate this data using a spreadsheet and import it (or pure SQL if you are hardcore ;)
Quick example using Standard SQL:
Say there are only five Items in the set:
CREATE TABLE Items
(
item_ID INTEGER NOT NULL UNIQUE
);
INSERT INTO Items (item_ID)
VALUES (1),
(2),
(3),
(4),
(5);
You lookup table would be as simple as this:
CREATE TABLE ItemsOfTheDay
(
cal_date DATE NOT NULL UNIQUE,
item_ID INTEGER NOT NULL
REFERENCES Items (item_ID)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
Starting with today, add the whole set of Items in random order:
INSERT INTO Items (item_ID)
VALUES ('2010-07-13', 2),
('2010-07-14', 4),
('2010-07-15', 5),
('2010-07-16', 1),
('2010-07-17', 3);
Then, starting with the most recent unfilled date, add the whole set of Items in (hopefully a different) random order:
INSERT INTO Items (item_ID)
VALUES ('2010-07-18', 1),
('2010-07-19', 3),
('2010-07-20', 4),
('2010-07-21', 5),
('2010-07-22', 2);
...and again...
INSERT INTO Items (item_ID)
VALUES ('2010-07-23', 2),
('2010-07-24', 3),
('2010-07-25', 5),
('2010-07-26', 1),
('2010-07-27', 4);
..and so on until the table is full.
Then it would then simply be a case of looking up today's date in the lookup table as and when required.
If the set of Items changes then the lookup table would obviously need to be regenerated, so you need to balance out the simplicity of design against the need for manual maintenance.
If you have fixed items you can add column
ALTER TABLE your_table ADD COLUMN item_day INT DEFAULT 0;
then selecting item use
WHERE item_day = DATE_FORMAT('%j')
If you get empty result then you can format new list of day items:
<?php
$qry = " UPDATE your_table SET item_day = 0";
$db->execute($qry);
// You only need 355 item to set as item of the day
for($i = 0; $i < 355; $i++) {
$qry = "UPDATE your_table SET item_day = ".($i+1)." WHERE item_day = 0 ORDER BY RAND() LIMIT 1";
$rs = $db->execute($qry);
// If no items left stop update
if (!$rs) { break; }
}
?>
Here's a stored procedure which selects a random row without using ORDER BY RAND(), and which resets the used flag once all items have been used:
DELIMITER //
DROP PROCEDURE IF EXISTS random_iotd//
CREATE PROCEDURE random_iotd()
BEGIN
# Reset used flag if all the rows have been used.
SELECT COUNT(*) INTO #used FROM iotd WHERE used = 1;
SELECT COUNT(*) INTO #rows FROM iotd;
IF (#used = #rows) THEN
UPDATE iotd SET used = 0;
END IF;
# Select a random number between 1 and the number of unused rows.
SELECT FLOOR(RAND() * (#rows - #used)) INTO #rand;
# Select the id of the row at position #rand.
PREPARE stmt FROM 'SELECT id INTO #id FROM iotd WHERE used = 0 LIMIT ?,1';
EXECUTE stmt USING #rand;
# Select the row where id = #id.
PREPARE stmt FROM 'SELECT id, item FROM iotd WHERE id = ?';
EXECUTE stmt USING #id;
# Update the row where id = #id.
PREPARE stmt FROM 'UPDATE iotd SET used = 1 WHERE id = ?';
EXECUTE stmt USING #id;
DEALLOCATE PREPARE stmt;
END;
//
DELIMITER ;
To use:
CALL random_iotd();
The procedure assumes a table structure like this:
CREATE TABLE `iotd` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item` varchar(255) NOT NULL,
`used` BOOLEAN NOT NULL DEFAULT 0,
INDEX `used` (`used`),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Here's one way to get the result from PHP (to keep things simple, error checking has been removed):
$mysqli = new mysqli('localhost', 'root', 'password', 'database');
$stmt = $mysqli->prepare('CALL random_iotd()');
$stmt->execute();
$stmt->bind_result($id, $item);
$stmt->fetch();
echo "$id, $item\n";
// 4, Item 4
UPADATE
This version should return the same result repeatedly on a given date. I've not really had time to test this, so be sure to do some testing of your own...
DELIMITER //
DROP PROCEDURE IF EXISTS random_iotd//
CREATE PROCEDURE random_iotd()
BEGIN
# Get today's item.
SET #id := NULL;
SELECT id INTO #id FROM iotd WHERE ts = CURRENT_DATE();
IF ISNULL(#id) THEN
# Reset used flag if all the rows have been used.
SELECT COUNT(*) INTO #used FROM iotd WHERE used = 1;
SELECT COUNT(*) INTO #rows FROM iotd;
IF (#used = #rows) THEN
UPDATE iotd SET used = 0;
END IF;
# Select a random number between 1 and the number of unused rows.
SELECT FLOOR(RAND() * (#rows - #used)) INTO #rand;
# Select the id of the row at position #rand.
PREPARE stmt FROM 'SELECT id INTO #id FROM iotd WHERE used = 0 LIMIT ?,1';
EXECUTE stmt USING #rand;
# Update the row where id = #id.
PREPARE stmt FROM 'UPDATE iotd SET used = 1, ts = CURRENT_DATE() WHERE id = ?';
EXECUTE stmt USING #id;
END IF;
# Select the row where id = #id.
PREPARE stmt FROM 'SELECT id, item FROM iotd WHERE id = ?';
EXECUTE stmt USING #id;
DEALLOCATE PREPARE stmt;
END;
//
DELIMITER ;
And the table structure:
CREATE TABLE `iotd` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item` varchar(255) NOT NULL,
`used` BOOLEAN NOT NULL DEFAULT 0,
`ts` DATE DEFAULT 0,
INDEX `used` (`used`),
INDEX `ts` (`ts`),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Why don't you use sequence?
Sequence serves your purpose easily...