Having various troubles with Insert Into - mysql

I have an extension I have made and inside this extension there is an "install.sql" file which contains various inserts.
Some of these inserts do it to tables which MAY exist or not depending on the clients site. What I would like to know is how to do for example something like:
"create table if exists" but for an "Insert Into".
This is an example of what im doing:
INSERT INTO `#__virtuemart_shipmentmethods_en_gb`
(virtuemart_shipmentmethod_id, shipment_name, shipment_desc, slug)
VALUES ((SELECT MAX(vs.virtuemart_shipmentmethod_id)
FROM `#__virtuemart_shipmentmethods` vs), 'Kiala','', 'kiala');
Thanks in advance for your help.

i don't know if i got your question right....
you want to insert somesthing and if its already there you want to update ?
if yes, you propably looking for THIS HERE otherwise your question is set up bad or its to late for me to get it right :)
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
if you don't know if the table exists than you might should check all befor
usual i use pdo, don't know what you use but my solution would be some like this
$result = mysql_query("SHOW TABLES LIKE '#__virtuemart_shipmentmethods_en_gb'");
$tExists = mysql_num_rows($result) > 0;
if(!$tExists)
// Create Table Code here

Have you considered running this is a stored procedure? Something like
CREATE PROCEDURE `testprocdure` ()
BEGIN
IF (SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '#__virtuemart_shipmentmethods_en_gb') = 1 THEN
INSERT INTO `#__virtuemart_shipmentmethods_en_gb` (virtuemart_shipmentmethod_id, shipment_name, shipment_desc, slug)
VALUES ((SELECT MAX(vs.virtuemart_shipmentmethod_id) FROM `#__virtuemart_shipmentmethods` vs), 'Kiala','', 'kiala');
ELSE
-- Handle if the table doesnt exists
SELECT ''; -- This is just so the SP wont return a error after the else. Remove this when you want to run it
END IF;
END
You could also make use of parameters if you have variable changing.
Then the create syntax should look like this
CREATE PROCEDURE `testprocdure` (IN p_TableName VARCHAR(100))
Change the name of the parameter and datatype to fit your needs.
Could this maybe help?

Related

SQL check if existing row, if not insert and return it

I'm having a problem with my sql query. I need to insert a data that needs to be checked first if it is existing or not. If the data is existing the sql query must return it, if not insert and return it. I already google it but the result is not quite suitable to my problem. I already read this.
Check if a row exists, otherwise insert
How to 'insert if not exists' in MySQL?
Here is a query that' I'm thinking.
INSERT INTO #tablename(#field, #conditional_field, #field, #conditional_field)
VALUES(
"value of field"
(SQL QUERY THAT CHECK IF THERE IS AN EXISTING DATA, IF NOT INSERT THE DATA and RETURN IT, IF YES return it),
"value of feild",
(SQL QUERY THAT CHECK IF THERE IS AN EXISTING DATA, IF NOT INSERT THE DATA and RETURN IT, IF YES return it)
);
Please take note that the conditional field is a required field so it can't be NULL.
Your tag set is quite weird, I'm unsure you require all the technologies listed but as long as Firebird is concerned there's UPDATE OR INSERT (link) construction.
The code could be like
UPDATE OR INSERT INTO aTable
VALUES (...)
MATCHING (ID, SomeColumn)
RETURNING ID, SomeColumn
Note that this will only work for PK match, no complex logic available. If that's not an option, you could use EXECUTE BLOCK which has all the power of stored procedures but is executed as usual query. And you'll get into concurrent update error if two clients execute updates at one time.
You could split it out into 2 steps
1. run a select statement to retrieve the rows that match your valus. select count (*) will give you the number of rows
2. If zero rows found, then run the insert to add the new values.
Alternatively, you could create a unique index form all your columns. If you try to insert a row where all the values exist, an error will be returned. You could then run a select statement to get the ID for this existing row. Otherwise, the insert will work.
You can check with if exists(select count(*) from #tablename) to see if there is data, but with insert into you need to insert data for all columns, so if there is only #field missing, you cant insert values with insert into, you will need to update the table and go with a little different method. And im not sure, why do you check every row? You know for every row what is missing? Are you comparing with some other table?
You can achieve it using MySQL stored procedure
Sample MySQL stored procedure
CREATE TABLE MyTable
(`ID` int, `ConditionField` varchar(10))
;
INSERT INTO MyTable
(`ID`, `ConditionField`)
VALUES
(1, 'Condition1'),
(1, 'Condition2')
;
CREATE PROCEDURE simpleproc (IN identifier INT,ConditionData varchar(10))
BEGIN
IF (SELECT ID FROM MyTable WHERE `ConditionField`=ConditionData) THEN
BEGIN
SELECT * FROM MyTable WHERE `ConditionField`=ConditionData;
END;
ELSE
BEGIN
INSERT INTO MyTable VALUES (identifier,ConditionData);
SELECT * FROM MyTable WHERE `ConditionField`=ConditionData;
END;
END IF;
END//
To Call stored procedure
CALL simpleproc(3,'Condition3');
DEMO

Use Replace Clause in Insert Stataement for MYSQL

I am using MySQL database. I want to insert data into it. But one column data contains special characters. (backslash) I want to replace it with Double backslash and then execute Insert query.
Can we do it using Insert Query?
While looking for the answer I came across
UPDATE your_table
SET your_field = REPLACE(your_field, '/', '//')
WHERE your_field LIKE '%articles/updates/%'
So it is possible use Replace in Update query.
Can we do the same in insert query? Please Let me know if you can help me.
You can use the following:
REPLACE INTO table_name(column_name1,column_name2,…)
VALUES(value1,value2,…)
More info from:
http://www.mysqltutorial.org/mysql-replace.aspx
You can use a BEFORE INSERT TRIGGER on your table
CREATE TRIGGER trigger_name
BEFORE INSERT
ON my_table
FOR EACH ROW
SET NEW.col_name = IF(NEW.col_name = '/','//',NEW.col_name);

MySQL: IF table exists, truncate and insert ELSE create

Working only with MySQL (I have essentially no PHP knowledge), I need to have a table that's essentially a subset from a much larger table. The source table changes from time to time, losing some entries, gaining other new ones, and values changing for existing ones. I can describe what I want to happen, but can't seem to figure out a syntax of commands to make it work. I also know I can have two separate queries and just run whichever one I need, and I have that worked out, but I'd like to combine them if possible. Here's what I want:
IF the subset_table DOES NOT EXIST, create it as [select query], ELSE truncate the subset_table and insert [select query]
Like I said, I know there are other ways to do this - I could drop if exists/create, or I could just have two different sql files to run. I just want to know if I can do this as specified above.
Thoughts?
You can do this:
create table if not exists <tablename> . . .;
truncate table <tablename>;
insert into <tablename>(cols)
select blah blahblah . . .;
You don't need any if statements at all.
This can also be done through an SP (stored procedure)... makes it more readable and safe
DELIMITER $$
DROP PROCEDURE IF EXISTS `create_table_sp`$$
CREATE PROCEDURE `create_table_sp`()
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.TABLES WHERE table_name = '<table_name>'
AND table_schema = DATABASE() AND table_type = 'BASE TABLE') THEN
CREATE TABLE <subset_table_name>
AS SELECT * FROM <main_table_name>;
ELSE
TRUNCATE TABLE <subset_table_name>;
INSERT INTO <subset_table_name>
AS SELECT * FROM <main_table_name>;
END IF;
END$$
DELIMITER ;
CALL `create_table_sp`;
DROP PROCEDURE IF EXISTS `create_table_sp`;
There is also another way,
You could pass the table names as arguments to the SP, in this case sub_table_name and main_table_name
Make the above DML statements to a string using CONCAT()
Create a prepared statement out of it and execute
Hope this helped....

mysql_query INSERT in to table where

I want to insert into a table where user id = to something
And change o to 1 which means user is online
Tried this
mysql_query("INSERT INTO `20s` VALUES('','','','','','','',1) WHERE `uid`='$user_id ");
But that doesn't get me anywhere. What's the right syntax?
Also what's the best way to keep a record of online friends in the database?
TIP:it's better to use update here
Correct syntax for insert query is:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
but you need here is update query, so you may update already existing row:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You only need to change one column bit that show online so dont change other columns:
UPDATE `tableName` SET `columnForOnline`=1 WHERE user_id=online_user_id
There is no WHERE clause in INSERT statements (see MySQL documentation).
If you want to update a value in an existing row, use UPDATE:
UPDATE `20s` SET `online`=1 WHERE user_id=your_user_id
mysql_ functions are deprecated, use PDO or mysqli_ instead!
MySQL also supports REPLACE INTO, which follows the same syntax as INSERT. Be careful though, columns that you do not supply will be set to their defaults.
In your case:
REPLACE INTO `20s` VALUES('','','','','','','',1) WHERE `uid`= '$user_id'
(Plus, you are missing a closing quote ' at the end of your query)
Use update query instead of insert
UPDATE `tableName` SET `columnForOnline`=1 WHERE user_id=online_user_id

Is the Sql2008 MERGE syntax what I should be doing, here?

I've got a classic case of UPDATE or INSERTing some data into a table. I'm not sure if I should just do an UPDATE and if i get zero ROWCOUNT, then do an INSERT. Alternatively, I've heard rumours that the MERGE statement now replaces this, but I'm not sure how and if it's appropriate, in this situation.
Here's some sample sql to help demonstrate this...
ALTER PROCEDURE [dbo].[InsertLocationName]
(
#SomeId INTEGER,
#SomeName NVARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
UPDATE TableFoo
SET SomeName = #SomeName
WHERE SomeId = #SomeId
-- Did we update something?
IF ##ROWCOUNT <= 0
-- Nope, so add the record.
INSERT INTO TableFoo
VALUES (#SomeName)
END
thoughts?
Sure - the MERGE syntax is probably the easiest. You basically need:
a target table to update
a source table to read from
a JOIN condition
a bunch of statement to execute for matched or non-matched rows.
So it basically looks something like this:
MERGE TableFoo as t
USING TableFooSource as s
ON t.SomeID = s.SomeID
WHEN MATCHED THEN
UPDATE SET t.SomeName = s.SomeName
WHEN NOT MATCHED THEN
INSERT(SomeName) VALUES(s.SomeName)
;
Don't forget the semicolon at the end!!
Marc
PS: Updated to use your table and field names. The point here is - the set of data used to be updated needs to be in a source table of its own (if needed, bulk-import that from e.g. an external file) and then the whole operation (all INSERTs and UPDATEs) are done in a single SQL statement.
Bit more of an explanation here: http://www.databasejournal.com/features/mssql/article.php/3739131/UPSERT-Functionality-in-SQL-Server-2008.htm