Pass string in values of mysql insert query - mysql

How can i pass string in values rather than passing each value.
Receiving error
Error Code: 1136. Column count doesn't match value count at row 1
INSERT INTO `ProfileResumeActivityLog`
(`Email`,`ProfileID`,`ExternalUserDID`, `EventType`, `ResumeDID`, `EventText`, `CreatedOn`)
VALUES('checkpp#test.com,73443358,XR2Z1WT6WR5PPR6Z99L4,r
esume_backload,R3W6WN6LFY95PKL27SR,resume_create, NOW()' );
I want to pass this as string because my stored procedure takes dynamic number of values for batch insert
CREATE DEFINER=`root`#`localhost` PROCEDURE `SaveBatchMultipleProfileResumeActivityLog`(
_resumeBatch TEXT
)
BEGIN
INSERT INTO `ProfileResumeActivityLog`
(`Email`,`ProfileID`,`ExternalUserDID`, `EventType`, `ResumeDID`, `EventText`, `CreatedOn`)
VALUES(_resumeBatch);
END
calling
CALL CBAX.SaveBatchMultipleProfileResumeActivityLog ('checkpp#test.com,73443358,XR2Z1WT6WR5PPR6Z99L4,resume_backload,R3W6WN6LFY95PKL27SR,resume_create, NOW()',
'checkpp#test1.com,73443358,XR2Z1WT6WR5PPR6Z99L41,resume_backload,R3W6WN6LFY95PKL27SR1,resume_create, NOW()' )

when you put string inside a insert statement you have to put them inside a "" thats why you get that error.
INSERT INTO `ProfileResumeActivityLog`(`Email`,`ProfileID`,`ExternalUserDID`, `EventType`, `ResumeDID`, `EventText`, `CreatedOn`)
VALUES('checkpp#test.com',73443358,'XR2Z1WT6WR5PPR6Z99L4','resume_backload','R3W6WN6LFY95PKL27SR','resume_create', NOW() );

Related

Is there a way to store the value of a variable in a table using INSERT in Myssql

I am using MySQL Workbench 8.0 and would like to store the value of a variable in a table using INSERT.
Let's say:
I have a function defined as func which return a decimal.
I have a stored procedure defined as storedProcedure which takes two parameters.
Inside the stored procedure, I would like to store the returned value of the function in a variable then insert all three values (two parameters + one returned result) in an existing table.
Here is what I unsuccessfully tried so far:
CREATE DEFINER=`user`#`localhost` PROCEDURE `storedProcedure`(
IN param1 BOOL,
IN param2 INTEGER(10)
)
BEGIN
DECLARE returnedValue DECIMAL(7,2);
SET #returnedValue = (SELECT func());
INSERT INTO existing_db.existing_table (
column1,
column2,
column3
)
VALUES(
#param1,
#param2,
#returnedValue
);
END
When executing call storedProcedure(param1Value, param2Value) in a query tab, the console returns the
error code 1048: column cannot be null.
PS:
During debugging, I noticed that the function works correctly and returns a value which is effectively store in the variable.
I also tried to access the value in variables using (select #resultAG) in the VALUES section of the INSERT statement.
Thanks in advance,
CREATE DEFINER=`user`#`localhost`
PROCEDURE `storedProcedure`(
IN param1 BOOL,
IN param2 INTEGER(10)
)
INSERT INTO existing_db.existing_table (
column1,
column2,
column3
)
VALUES(
param1,
param2,
func()
);
If you want not only save the value returned by the function into the table but use this returned value into the variable for future use in the connection code also then use
CREATE DEFINER=`user`#`localhost`
PROCEDURE `storedProcedure`(
IN param1 BOOL,
IN param2 INTEGER(10)
)
INSERT INTO existing_db.existing_table (
column1,
column2,
column3
)
SELECT
param1,
param2,
#returnedValue := func()
;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=daaa2e7409dfc4e5e00675153134da9d

Postgres JSON Array data processing

Have a table "json_test" and inserted the following record:
create table json_test ( v json);
insert into json_test values ('{"facilityId": ["20","30","40","50","51"]}')
SELECT trim(json_array_elements_text(v->'facilityId') ) from json_test
The above select lists the facility ID as individual rows.
I need the same rows in a Postgres function to insert the record into another table. I wrote the following code to return i. The output of the v_status when checked is (20,,,,,,,,,,,,). I need to get just 20, but I am unable to get that.
for i in SELECT json_array_elements_text(v->'facilityId') from json_test
loop
v_status:= i;
end loop;
You have not specified entire function definition in your question.
Assuming you have DDL:
CREATE TABLE json_test(
id SERIAL PRIMARY KEY,
v JSON
);
INSERT INTO json_test(v) VALUES
('{"facilityId": ["20","30","40","50","51"]}'::JSON);
You can check full PL/pgSQL guide as a reference, but your function may be defined as the following:
CREATE OR REPLACE FUNCTION get_facility_ids(rid INTEGER)
RETURNS SETOF INTEGER AS $$
DECLARE
t TEXT;
BEGIN
FOR t IN SELECT json_array_elements_text(v->'facilityId')
FROM json_test WHERE id = rid
LOOP
RETURN NEXT t;
END LOOP;
END;
$$ LANGUAGE plpgsql;
SELECT get_facility_ids(1) AS facultyId;
Just for your information, you can INSERT records from SELECT statements. Check the documentation.

MySQL Trigger Error using variables

I'm trying to get the following code to run in a MySQL Trigger but I get error 1064 when I try to save it.
SET #ma = (SELECT modem_alias FROM `play`.`veh` WHERE meid = new.org_a LIMIT 1);
INSERT INTO `play`.`des` (`indx`, `des_a`, `des_b`) VALUES (NULL, new.org_a, SELECT #ma);
The trigger is set to run on 'org' table after an INSERT
Don't use SELECT in the INSERT, just the variable:
INSERT INTO `play`.`des` (`indx`, `des_a`, `des_b`) VALUES (NULL, new.org_a, #ma);
You can also combine the two queries so you don't need a variable:
INSERT INTO play.des (indx, des_a, des_b)
SELECT NULL, new.org_a, modem_alias
FROM play.veh
WHERE meid = new.org_a
LIMIT 1
Your values is wrong: You can't select there, just use the variable itself:
INSERT ... VALUES (..., #ma);

IF NOT EXISTS in mysql showing syntax error

I am trying to convert this tsql to mysql but showing error need help
CREATE PROCEDURE FormAdd
#formName varchar(MAX)
AS
IF NOT EXISTS(SELECT * FROM tbl_Form WHERE formName=#formName)
BEGIN
INSERT INTO tbl_Form
(formName)
VALUES
(#formName)
SELECT ##identity
END
ELSE
BEGIN
SELECT '-1'
END
mysql
CREATE PROCEDURE FormAdd
(p_formName varchar(500) )
begin
INSERT INTO tbl_Form (formName)
VALUES (p_formName)
where NOT EXISTS(SELECT * FROM tbl_Form WHERE formName=p_formName) ;
SELECT Last_insert_id() as returnvalue ;
SELECT '-1' ;
end
Your attempt was syntactically invalid because logically, an INSERT statement cannot contain a WHERE clause since it does not act on existing rows.
If the purpose is to insert only if the value for p_formname is not already present, then an appropriate step would be to define a unique index on that column first. Then, construct your procedure to attempt the insert and inspect the ROW_COUNT() value to see if one was inserted and act accordingly, returning -1 if not to adapt your existing T-SQL procedure.
First create the unique index on p_formname:
ALTER TABLE tbl_Form ADD UNIQUE KEY `idx_formName` (`formName`);
Then your procedure should use INSERT INTO...ON DUPLICATE KEY UPDATE to attempt to insert the row. Per the documentation, the value of ROW_COUNT() will be 0 if a new row was not inserted or 1 if it was.
CREATE PROCEDURE FormAdd (p_formName varchar(500))
BEGIN
/* Attempt the insert, overwrite with the same value if necessary */
INSERT INTO tbl_Form (formName) VALUES (p_formName) ON DUPLICATE KEY UPDATE formName = p_formName;
/* Return the LAST_INSERT_ID() for a new row and -1 otherwise */
SELECT
CASE
WHEN ROW_COUNT() = 1 THEN LAST_INSERT_ID()
ELSE -1
END AS returnValue;
END

How to select into a variable in SQL when the result might be null?

I have the following stored procedure:
DELIMITER //
CREATE PROCEDURE NewSeqType(IN mySubschemaID INT, IN hashVal bigint(20))
BEGIN
DECLARE newSeqTypeID INT;
SELECT MAX(ID)+1 INTO newSeqTypeID FROM sequenceType WHERE subschemaID=mySubschemaID;
INSERT INTO SequenceType(ID, HashValue, subschemaID) VALUES(newSeqTypeID, hashVal, mySubschemaID);
SELECT LAST_INSERT_ID() as ID; -- return prim key
END//
This works when there is already data in the table where subschemaID=mySubschemaID, but if that SELECT statement returns null, then the MAX(ID)+1 part gives the error column ID cannot be null.
How can I give ID a default value, say 0, in that case?
For this, you can use coalesce():
SELECT coalesce(MAX(ID)+1, 1) INTO newSeqTypeID FROM sequenceType WHERE subschemaID=mySubschemaID;
INSERT INTO SequenceType(ID, HashValue, subschemaID) VALUES(newSeqTypeID, hashVal, mySubschemaID);
Often, this type of work is done in a before insert trigger, to keep the values aligned.