Query cf queryObject and insert into table - mysql

I'm passing queryObject into a CFC. I can writeDump(myQryObject) and I see the queryObjects contents and all is good up to this point. I can write a select statement and dump a row(s) depending on my query - again, all good here. I need to now insert the data into a table but I'm not getting the syntax right.
The CFC is written in CFScript.
local.blkLoadQry = new Query(); // new query object
local.blkLoadQry.setDBType("query");
local.blkLoadQry.setAttributes(sourceQuery=arguments.blkdata);
local.blkLoadQry.addParam(name="batchid",value=arguments.batchID,cfsqltype="cf_sql_varchar",maxlength="36");
local.blkLoadQry.setSQL("
INSERT INTO bulkloadtemptable (
uuid
, gradyear
, firstName
, lastName
, email
)
SELECT
:batchid
, `Graduation Year`
, `Jersey`
, `First Name`
, `Last Name`
, `Email`
FROM
bulkloadtemptable_copy
WHERE uuid = :batchid
");
`Lexical error at line 10, column 17. Encountered: "`" (96), after : ""`
This is the error I'm getting but the line numbers of the errors don't line up with my expectations so that's what brings me here. :batchid would be line 10.
What am I missing?

You are attempting something impossible. Your query of queries select statement runs in ColdFusion only. There is no database connection in play.
If you want to insert data from a ColdFusion query into a database, you have to loop through the rows somehow. You can have an insert query inside a loop or a loop inside an insert query. Here is sample syntax for both.
Query inside loop.
<cfoutput query="cfQueryObject">
<cfquery datasource = "aRealDatabase">
insert into table
(field1
, field2
, etc)
values
(<cfqueryparam value = "#cfQueryObject.field1#">
, <cfqueryparam value = "#cfQueryObject.field1#">
, etc
)
</cfquery>
</cfoutput>
Loop inside query
<cfquery datasource = "aRealDatabase">
insert into table
(field1
, field2
, etc)
select null
, null
, etc
from someSmallTable
where 1 = 2
<cfoutput query="cfQueryObject">
union
select <cfqueryparam value = "#cfQueryObject.field1#">
, <cfqueryparam value = "#cfQueryObject.field1#">
, etc
from someSmallTable
</cfoutput>
</cfquery>
You can experiment to see what works better in your situation.

Related

Update query in SQL: command not ended properly

update fare_strategy set sales_date_to = ’07-SEP-22’
where dep_date_to is not null
and market_id in
(select market_id
from fare_strategy_markets
where set_type = ‘STANDARD’
);
In the following query, I'm getting error as SQL command not properly ended.
try to change like this because in your query you used ’ this is not valid so i just change it to ' so it's works fine
update fare_strategy set sales_date_to = '07-SEP-22' where dep_date_to is
not null and market_id in (select market_id from
fare_strategy_markets where set_type = 'STANDARD');

Sequelize returns different value than MySql result

I have something very odd happening and nothing seems to work. I have a SP in MySql that returns some results. When I run the SP in MySql workbench everything is correct. The query is quite long. But this is the LEFT JOIN is somehow creating the issues. I have other inner joins/left joins but they are fine.
SELECT DISTINCT Id.ReelTag
, Id.ECSPartNo
, WM.ShortDescription AS Description
, Id.ReelTagSerial
, group_concat(DISTINCT RA.UniqueID) AS UniqueID
, group_concat(DISTINCT coalesce(RA.OrdNo, Std.OrdNo)) AS OrdNo
, Id.Received
, IFNULL(Std.ReelQuantity,0) AS OriginalQuantity
, IFNULL(Id.Quantity,0) AS CurrentQuantity
, IFNULL(yest.Quantity,0) AS YesterdayQuantity
, IFNULL(cuts.Quantity,0) AS QuantityChanged
, cuts.OrdNo AS OrdNoChange
, IFNULL(CC.ShipQuantity,0) AS ShipQuantity
, CC.OrdNo AS OrdNo_Allocated
, IFNULL(Id.Quantity,0) - IFNULL(yest.Quantity,0) AS changeAOF_Yesterday
FROM InventoryDtl Id .....
LEFT JOIN (
SELECT
SourceReel
, SUM(CASE WHEN Action = 'Insert' THEN TotalQuantity
WHEN Action = 'Delete' THEN -TotalQuantity
ELSE 0 END) AS Quantity
, group_concat(DISTINCT CASE WHEN Action = 'Insert' THEN concat(OrdNo,'(Cut)') ELSE concat(OrdNo,'(UnCut)') END) AS OrdNo
FROM (
SELECT
Action
, SourceReel
, OrdNo
, SUM(Quantity) AS TotalQuantity
FROM CableCuts_Log CD
WHERE 1=1
AND 1 = CASE
WHEN SourceReel IS NOT NULL AND OrdNo LIKE 'E9%' AND Quantity > 0 AND DaTediff(Now(),LogDate) = 0 THEN 1
ELSE 0 END
GROUP BY Action, SourceReel, OrdNo
) CC
WHERE 1=1
GROUP BY SourceReel
) cuts ON Id.ReelTag = cuts.SourceReel
Again, When I run this in MySql workbench it's fine and loads in a second if that makes a difference.
But when I call my API to call the SP using ...
let inventoryReport = await models.sequelize
.query(
`call rpt_DailyInventoryReport($location, $byECSPartNo);`,
{ bind: {location: req.body.location, byECSPartNo: null} },
)
for(i=0;i<inventoryReport.length;i++) {
if(inventoryReport[i].ReelTagSerial == '6906' || inventoryReport[i].ReelTagSerial == '6858') {
console.log(inventoryReport[i]);
}
}
and exporting that into an Excel using ExcelJS, the 2 "cuts" columns from the query are essentially NULLs, because the return value of the "cuts" select are coming up NULLS, which is why it's giving the IFNULL value instead. Again this work in MySql workbench.
These are the values the API throws out.
{
"ReelTagSerial": 6858,
"CurrentQuantity": 700,
"YesterdayQuantity": 2500,
"QuantityChanged": 0,
"OrdNoChange": null,
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -1800
},
{
"ReelTagSerial": 6906,
"CurrentQuantity": 2730,
"YesterdayQuantity": 3330,
"QuantityChanged": 0,
"OrdNoChange": null,
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -600
},
Here are the 2 rows that their values should be.
{
"ReelTagSerial": 6906,
"CurrentQuantity": 2730,
"YesterdayQuantity": 3330,
"QuantityChanged": 600,
"OrdNoChange": E92021(Cut),
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -600
}
{
"ReelTagSerial": 6858,
"CurrentQuantity": 700,
"YesterdayQuantity": 2500,
"QuantityChanged": 1800,
"OrdNoChange": E912345(Cut),
"ShipQuantity": 0,
"OrdNo_Allocated": null,
"changeAOF_Yesterday": -1800
},
I have tried creating a temp table and defining the field type of varchar, text, mediumint for the QuantityChanged field.
At first I thought maybe ExcelJs was not liking the key/value pairs but then I simply console logged the 2 rows and they are returning like that from Sequelize. I have tried casting the 2 fields with every datatype possible.
, CAST(cuts.OrdNo AS char) AS OrdNoChange
, CAST(cuts.OrdNo AS binary) AS OrdNoChange
Now I am just immediately sending the return result as a response back to Postman and seeing all the rows to make sure for whatever reason those values are not being set in other rows. But they seem to be all good.
If I simply rearrange the columns so that the two bad fields get values of other fields, they do populate with their values, so that's about as far as I got. Or if I put just 1000 or a string type it returns correctly, so IT MUST be something to do with those 2 data types from the "cuts" query.
I have tried returning simply returning these from the "cuts" join query
SELECT
DISTINCT SourceReel
#, CAST(SUM(CASE WHEN Action = 'Insert' THEN TotalQuantity
# WHEN Action = 'Delete' THEN -TotalQuantity
# ELSE 0 END) AS UnSigned) AS Quantity
, SUM(TotalQuantity) AS Quantity
, OrdNo
#, group_concat(DISTINCT CASE WHEN Action = 'Insert' THEN concat(OrdNo,'(Cut)') ELSE concat(OrdNo,'(UnCut)') END) AS OrdNo
Nothing is working. Spent hours troubleshooting and searching...
Need some help please :)
Thanks in advance.
I was able to get around this by creating a table and inserting into it during the SP call. Then in NodeJs I created a model of that table and just used to find everything in the table immediately after I called the SP.
let inventoryReport = await models.Rpt_DailyInventory_Temp.findAll();
Then just TRUNCATE the table every time the SP is called.

SQL Server: How to query data all rows as Json object into next to other columns?

I have data like this:
I want to query result like this:
Here is my code
SELECT
PML_CODE
,PML_NAME_ENG
,(
SELECT
PML_ID
,PML_NO
,PML_CODE
,PML_NAME_ENG
,PML_FORMULA
FROM DSP.PARAMET_LIST AS A WITH(NOLOCK)
WHERE A.PML_ID = B.PML_ID
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) AS BR_OBJECT
FROM DSP.PARAMET_LIST AS B WITH(NOLOCK)
My code works for what I want, but I want to know if there is a better, faster way to write this query?
Next time please do not post pictures, but rather try to create some DDL, fill it with sample data and state your own attempts and the expected output. This makes it easier for us to understand and to answer your issue.
You can try it like this:
DECLARE #tbl TABLE(PML_ID BIGINT, PML_NO INT, PML_CODE VARCHAR(10), PML_NAME_ENG VARCHAR(10), PML_FORMULA VARCHAR(10));
INSERT INTO #tbl VALUES
(2017102600050,1,'KHR','Riel','01')
,(2017102600051,2,'USD','Dollar','02')
,(2017102600052,3,'THB','Bath','05')
SELECT
PML_CODE
,PML_NAME_ENG
,BR_OBJECT
FROM #tbl
CROSS APPLY(
SELECT
(
SELECT
PML_ID
,PML_NO
,PML_CODE
,PML_NAME_ENG
,PML_FORMULA
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
)) AS A(BR_OBJECT);
The big difference to your own approach is that I use a CROSS APPLY using the columns we have already instead of calling a correlated sub-query.
You can just concatenate the values. Be sure to cast the integers and to handle the NULL values. For example, if there is NULL value for column, there can be two cases - ignore the property or add the property with null, right?
For SQL Server 2016 SP1+ and later you can use FOR JSON. Basically, you should end up with something like this:
DECLARE #DataSource TABLE
(
[PML_ID] VARCHAR(64)
,[PML_NO] INT
,[PML_CODE] VARCHAR(3)
,[PML_NAME_ENG] NVARCHAR(32)
,[PML_FORMULA] VARCHAR(2)
);
INSERT INTO #DataSource ([PML_ID], [PML_NO], [PML_CODE], [PML_NAME_ENG], [PML_FORMULA])
VALUES ('201710260000000050', 1, 'KHR', 'Riel', 01)
,('201710260000000051', 2, 'USD', 'Dollar', 02)
,('201710260000000052', 3, 'THB', 'Bath', 05);
SELECT [PML_CODE]
,[PML_NAME_ENG]
,'{"PML_ID":'+ [PML_ID] +',"PML_NO":'+ CAST([PML_NO] AS VARCHAR(12)) +',"PML_CODE":'+ [PML_CODE] +',"PML_NAME_ENG":'+ [PML_NAME_ENG] +',"PML_FORMULA":'+ [PML_FORMULA] +'}' AS [BR_OBJECT]
FROM #DataSource;
-- SQL Server 2016 SP1 and latter
SELECT DS1.[PML_CODE]
,DS1.[PML_NAME_ENG]
,DS.[BR_OBJECT]
FROM #DataSource DS1
CROSS APPLY
(
SELECT *
FROM #DataSource DS2
WHERE DS1.[PML_CODE] = DS2.[PML_CODE]
AND DS2.[PML_NAME_ENG] = DS2.[PML_NAME_ENG]
FOR JSON AUTO
) DS ([BR_OBJECT]);

MySQL any keyword usage

I am having the following issue:
When I execute the following statement, I get an error for it returning more than one row
INSERT INTO artist
(personid,
musicgenreid,
totallikes)
VALUES ( (SELECT personid
FROM person
WHERE firstname = 'Joe'
AND middlename = ''
AND lastname = 'blow'),
(SELECT musicgenreid
FROM musicgenre
WHERE musicgenreid = 4),
( totallikes = 328374 ) );
I am getting the error on the (select pesonID from person...) statement, and I am trying to use the 'any' keyword to just grab any row, but I cannot seem to get it to work. I have tried just about any permutation I can think of of the current query and 'any', but it does not work. Is there another solution I should be trying or am I just missing the mark for some reason?
It seems you're trying to do something like this:
INSERT INTO artist (personid, musicgenreid, totallikes)
VALUES (
(SELECT personid FROM person
WHERE firstname = 'Joe' AND middlename = '' AND lastname = 'blow'
ORDER BY RAND()
LIMIT 1
),
4,
328374
);
This will get you a random personid that matches the given criteria.
The musicgenreid in your query would be either null or 4. I am forcing it to 4 as it seems that you're manually adding them and you know they already exist.
The total likes field is also fixed but your syntax was incorrect.
try with this sql statement
INSERT INTO artist
(personid,
musicgenreid,
totallikes)
VALUES ( (SELECT personid
FROM person
WHERE firstname = 'Joe'
AND middlename = ''
AND lastname = 'blow' LIMIT 1 ),
4,
328374);

Inserting NULL into column?

I'm trying to figure out how I can insert a NULL value into a column of newly inserted row.
I'm working on "post icons" which will display a small icon for the thread on the thread list. The icons use RADIO buttons in the form. By default it is set to No Icon. I was wondering what to do for the value of that radio button to make it null? I tried setting value as NULL but it just inserts the word "NULL" into the database.
$thread_sql = "
INSERT INTO forum_threads (
user_id,
forum_id,
thread_postdate,
thread_lastpost,
thread_title,
thread_description,
thread_icon
) VALUES (
'$_SESSION[user_id]',
'$_GET[f]',
'$date',
'$date',
'$_POST[topictitle]',
'$_POST[topicdescription]',
'$_POST[posticon]'
)
";
$thread_query = #mysqli_query ($db_connect, $thread_sql);
With MySQL:
insert into your_table (nulled_column) values (null);
If you are getting a 'NULL' literal instead of a null value, it's probably because you are not issuing the right command from your client (PHP, C#, Java program). You will need to share the code you are using for your insertion in order to get more help.
UPDATE:
According to your recently edited question, just get rid of the '' when you are inserting NULL values. If you use '', then you'll get 'NULL' literals inserted as you mentioned.
I would also suggest you use PreparedStatements in MySQL in order to avoid SQL injection attacks.
Just do something like this (PDO):
$stmt = $db->prepare('INSERT INTO foo(bar) values (?);');
$stmt->execute(array($value=='NULL'? NULL,$value));
Or with mysql:
mysql_query('INSERT INTO foo(bar)
values ('.($value=='NULL'? 'NULL',"'".mysql_real_escape_string($value)."'").')';
This works. Had to use an IF
if (isset($_POST['submit'])) {
$thread_sql = "
INSERT INTO forum_threads (
user_id,
forum_id,
thread_postdate,
thread_lastpost,
thread_title,
thread_description,
thread_icon
) VALUES (
'$_SESSION[user_id]',
'$_GET[f]',
'$date',
'$date',
'$_POST[topictitle]',
'$_POST[topicdescription]',
IF('$_POST[posticon]'='NULL',NULL,'$_POST[posticon]')
)
";
$thread_query = #mysqli_query ($db_connect, $thread_sql);