Here is a sample of the Javascript, that I want to add an additional WHERE statement to the CONDITIONS variable.
In addition to Where Cost > 0, only include records where ProductName begins with "XYZ".
Maybe: AND ProductName StartsWith('XYZ') ??
REPORTS: [{NAME: 'MYREPORTNAME',
CONDITIONS: 'WHERE Cost > 0',
FIELDS: {'ProductSKU' : 'STRING',
'ProductName' : 'STRING',
'Cost' : 'FLOAT'
}
This is later called in this function:
function retrieveMyReport(reportConfig, ClientId) {
var fieldNames = Object.keys(reportConfig.FIELDS);
var report = MyApp.report(
'SELECT ' + fieldNames.join(',') +
' FROM ' + reportConfig.NAME + ' ' + reportConfig.CONDITIONS +
' DURING ' + CONFIG.DEFAULT_DATE_RANGE);
...
How do I expand this WHERE clause to include both conditions?
This looks like an SQL query, so you should probably use the LIKE operator:
CONDITIONS: 'WHERE Cost > 0 AND ProductName LIKE \'XYZ%\''
Related
I am creating a script that would show the keys of my array, in the first attempt worked perfectly, but when I added but a while block, he did not execute and returned this error:
classificacao-v2.js:128 Uncaught TypeError: Cannot read property 'Period' of undefined
at classificacao-v2.js:128
Realizing that my problem was in the variable 'n' that appeared as undefined, so I created other variables with different names for each structure.
I wonder if it is possible to rewrite it more efficiently without having to repeat each block.
let GoldemStates = [{Period: ' 1°',Points:'300'},
{Period: ' 2°',Points:'250'},
{Period: ' 3°', Points:'155'}]
let Chicago = [{Period: ' 1°',Points:'100'},
{Period: ' 2°',Points:'420'},
{Period: ' 3°', Points:'350'}]
let Broklyn = [{Period: ' 1°',Points:'300'},
{Period: ' 2°',Points:'250'},
{Period: ' 3°', Points:'155'}]
// Show the Teams
icons('','Match Results ','div_titulo')
let n = 0
icons('golden','Golden States', 'destaque_golden') //Team Title (Symbol, Team Name, CSS)
//Goldem States Statistics
do {
icons('clock',GoldemStates[n].Period + ' Period | ' + 'Points ' + GoldemStates[n].Points ,'texto') // // Show period and points
n ++
} while (n < GoldemStates.length);
let d = 0 // <-------- CHANGE WHICH WOULD NEED
//Chicago Bulls Statistics
icones('bulls','Chicago Bulls', 'destaque_bulls')//Team Title (Symbol, Team Name, CSS)
do {
icons('clock',Chicago[d].Period + ' Period | ' + 'Points ' + Chicago[d].Points ,'texto')// Show period and points
d ++
} while (d < Chicago.length);
Console Output
I think your code could be simpler, shorter and easier to read if you leave the iteration to array built in methods. That way you will remove the need to use an iteration variable and access each item:
GoldemStates.forEach(
item => icons('clock',item.Period + ' Period | ' + 'Points ' + item.Points ,'texto')
)
But we can do it eve better. Since all the teams render exactly the same, we can build a function that renders one single item and then let the methods specialized on iteration do their work. That way your code only takes care of rendering and the built-in methods takes care of iterating, separation of conerns:
const renderTeam = team => icons('clock',team.Period + ' Period | ' + 'Points ' + team.Points ,'texto')
// Render part
icons('golden','Golden States', 'destaque_golden') //Team Title (Symbol, Team Name, CSS)
GoldemStates.forEach(renderTeam)
icons('bulls','Chicago Bulls', 'destaque_bulls')//Team Title (Symbol, Team Name, CSS)
Chicago.forEach(renderTeam)
Referring to the sample SQL statement below. I'm able to pass parameter values to the placeholder '?' in the statement. However I'm wondering whether it is possible to pass in the sort order in the same way?
So instead of this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY transactionDate DESC " +
"LIMIT 20;"
);
Can I have this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY ? DESC " +
"LIMIT 20;"
);
And to invoke it:
//Invoke prepared SQL query and return invocation result
function getAccountTransactions1(accountId){
return WL.Server.invokeSQLStatement({
preparedStatement : getAccountsTransactionsStatement,
parameters : [accountId, accountId, transactionDate]
});
}
Two things:
This query piece:
WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ?
Could be replaced with this:
WHERE ? in (accounttransactions.fromAccount, accounttransactions.toAccount)
No you can't. Parameters are values - kind of static stuff - while column names are not. You could probably work around the issue somehow in limited way by using s.t. like this:
ORDER BY
CASE ?
WHEN 'transactionDate' THEN transactionDate
WHEN 'someotherdate' THEN someotherdate
ELSE DATE '2010-01-01'
END
Note however that's a messy construction. Also depending on the type of the database you're using you might want to cast all the columns into one data type i.e. string. so to_char(transactionDate,'yyyy-mm-dd hh24:mm:ss') might be in order but you need to ensure that the sorting is proper in your case (as number tend to mess stuff up like '2' > '13').
I will Update a Value in my Database when this is not setted.
I have this Code:
items.forEach(function(item,i,arr){
mysqlConnection.query('UPDATE `SkinBank` SET `AssetID`=\'' + item.assetid + '\', `Status`=\'market\' WHERE `Status`=\'open\' AND `Tradeoffer` = \'' + offer.id + '\' AND `SkinName` = \'' + item.market_hash_name + '\'', function (err, row, fields) {});
});
When i put than 2 "Items" which has item.assetid (like: Item 1 has = 123123 and Items 2 has= 987987) than all two items who has nothing get the same Assetid value like 123123 or 987987.
How i can make, that he gives every item ONE AssetId.
Before this, the column "AssetID" has nothing in there
I'm guessing that your WHERE clause is matching too many rows. It's not clear what library you are using, but if you are using node-mysql you can output the number of rows updated in the callback function:
connection.query('UPDATE `SkinBank` SET `AssetID`=\'' + item.assetid + '\', `Status`=\'market\' WHERE `Status`=\'open\' AND `Tradeoffer` = \'' + offer.id + '\' AND `SkinName` = \'' + item.market_hash_name + '\'', function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
})
https://github.com/felixge/node-mysql#getting-the-number-of-changed-rows
I use node.js and express.
I saved on the 'req.session' a complex object that includes array of objects.
In addition I save reference to one of the objects in the array.
For example:
var value = {
name: "name"
, values: []
};
req.session.value = value;
//
// I populate 'req.session.value' with values (with the same structure)
//
// then I save reference to one of the inner objects
var currentValue = req.session.value[3];
//
// later I try to change the save object
//
currentValue.name = "newName";
I expected that if I change the 'currentValue' then the 'req.session.value[3]' will be changed as well. However, for some reason it doesn't happen.
To be concrete, if I change the currentValue immediately after I assign it then the req.session.value[3] is changed but if I am doing it in the next call then just the currentValue is changed.
In the example: I do the assignments to the 'req.session' in the "app.get(...)" if I change the value of the currentValue in the "app.get(...)" it is run ok (the value change in both places) but if I change it in the 'app.post(...)' the only object that change is the currentValue while the req.session.value[3] left the same.
Thanks in advance,
Shai
The code:
'app.get("/template/:templateid/feature/add", isTemplate, function(req, res) {'
' if (!req.session.features) { // if features empty'
''
' // Save the first features level from the current template in the session '
' req.session.features = req.session.template.feature;'
' //'
' if (!req.session.featureNodes) { // featureNotes is a stack/branch of the features'
' req.session.featureNodes = [];'
' }'
' if (!req.query.featureroot || req.query.featureroot == "") {'
' } else {'
' var featureRoot = getFeature(req.query.featureroot, req.session.features); // get one object from req.session.features'
' if (featureRoot) {'
' req.session.featureNodes.push(featureRoot); // save reference'
' var featureR = req.session.featureNodes.pop(); // do check that work!'
' var values = {'
' name: "req.body.name"'
' , description: "req.body.description"'
' , wieght: "req.body.wieght"'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
''
' featureR.feature.push(values); // also req.session.features changed'
' req.session.featureNodes.push(featureRoot); // push the reference back for use later'
' } '
' }'
' res.render("addfeature2template.jade", { '
' title: "Add new feature"'
' ,template: req.session.template'
' ,feature: req.session.featureNodes'
' });'
'});'
''
'app.post("/feature/add", isUser, function(req, res) {'
' var SUBMIT = "Create";'
' var CANCEL = "Cancel";'
' switch ( req.param("feature") ) {'
' case SUBMIT:'
' var fields = { name: 1, description: 1, wieght: 1};'
' var values = {'
' name: req.body.name'
' , description: req.body.description'
' , wieght: req.body.wieght'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
' if (req.session.featureNodes.length < 1) {'
' req.session.features.push(values);'
' } else {'
' var featureRoot = req.session.featureNodes.pop(); // pop the reference'
' featureRoot.feature.push(values); // change the object but the req.session.features didnt changed '
' }'
' req.session.template = template;'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' case CANCEL:'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' }'
'});'
req.session object is serialized (to store) between the requests.
Example:
Request 1:
req.session = {};
var a = { hello : 'world' };
var b = a;
req.session.a = a;
req.session.b = b;
In this context variables a, b, req.session.a, req.session.b points to one object. You can change field hello in any of these objects, and this will to change in each of them.
After end of request req.session object will be serialized for session storage (memcached, mongodb, etc).
Request 2:
Before request 2 req.session object will be deserialized from storage. Now it contains plain values without references. You can access req.session.a and req.session.b but now it two different objects.
I have a view that I want to be converted into JSON. What is the SQL that I can use to produce on the server the JSON string needed to be returned?
--
-- Author: Thiago R. Santos --
-- Create date: Aug 3rd 2008 --
-- Description: Returns the contents of a given table --
-- in JavaScript Object Notation. --
-- Params: --
-- #table_name: the table to execute the query --
-- #registries_per_request: equivalent to "select top N * from table"
--
-- replcing N by the actual number
-- Influenced by Thomas Frank's post MySQL to JSON # January 23, 2007 --
-- Post Url: http://www.thomasfrank.se/mysql_to_json.html --
create procedure [dbo].[GetJSON]
(
#table_name varchar(50),
#registries_per_request smallint = null
)
as
begin
if((select count(*) from information_schema.tables where table_name = #table_name) > 0)
begin
declare #json varchar(max),
#line varchar(max),
#columns varchar(max),
#sql nvarchar(max),
#columnNavigator varchar(50),
#counter tinyint,
#size varchar(10)
if (#registries_per_request is null)
begin
set #size = ''
end
else
begin
set #size = 'top ' + convert(varchar, #registries_per_request)
end
set #columns = '{'
declare schemaCursor cursor
for select column_name from information_schema.columns where table_name = #table_name
open schemaCursor
fetch next from schemaCursor
into #columnNavigator
select #counter = count(*) from information_schema.columns where table_name = #table_name
while ##fetch_status = 0
begin
set #columns = #columns + '''''' + #columnNavigator + ''''':'''''' + convert(varchar, ' + #columnNavigator + ') + '''''''
set #counter = #counter - 1
if(0 != #counter)
begin
set #columns = #columns + ','
end
fetch next from schemaCursor
into #columnNavigator
end
set #columns = #columns + '}'
close schemaCursor
deallocate schemaCursor
set #json = '['
set #sql = 'select ' + #size + '''' + #columns + ''' as json into tmpJsonTable from ' + #table_name
exec sp_sqlexec #sql
select #counter = count(*) from tmpJsonTable
declare tmpCur cursor
for select * from tmpJsonTable
open tmpCur
fetch next from tmpCur
into #line
while ##fetch_status = 0
begin
set #counter = #counter - 1
set #json = #json + #line
if ( 0 != #counter )
begin
set #json = #json + ','
end
fetch next from tmpCur
into #line
end
set #json = #json + ']'
close tmpCur
deallocate tmpCur
drop table tmpJsonTable
select #json as json
end
end
I imagine this can be done, but it seems like an extremely long-winded and error-prone way of achieving the desired result.
If I were you I'd break down the problem into look at the ORM technology of your middle tier framework (ASP.NET I assume?) and then serialise to JSON again from the framework. Failing framework support (i.e. you aren't in .NET 3+) I'd still favour serialising the database to XML and then XSLT transforming the XML to JSON since XML is much much easier to work with on the server.
The name of the game is separation of concerns.
Below version is a total re-design of this concept. If I've missed something please add a note and I'll edit to adjust.
--
-- Author: Matthew D. Erwin (Snaptech, LLC)
-- Create date: May 9, 2013
-- Description: Returns the contents of a given table
-- in JavaScript Object Notation JSON -
--
-- Very notably useful for generating MOCK .json files
-- for testing or before RESTful services are completed.
--
-- This implementation:
-- *removed cursor (using FOR XML PATH(''))
-- *properly supports NULL vs quoted values
-- *supports dates in ISO 8601 - presuming UTC
-- *uses Data_Type and Is_Nullable info
-- *escapes '\'
-- *formats output with tabs/newlines
-- *can return final results as XML to bypass
-- truncation in SSMS
-- *supports schema (e.g. [dbo].[TableName]
-- *includes "recordCount" field
-- Options:
-- #table_name: the table to execute the query
-- #limit: equivalent to "select top N * from table"
-- #ssms: flag to use if executing in Sql Server Management Studio
-- to bypass result truncation limits.
--
-- Inspired primarily by the 2008 work of Thiago R. Santos which was influenced by Thomas Frank.
-- Usage: [dbo].[GetJSON] #Table_name = 'MySchema.MyTable', #limit = 50, #ssms = 0
create procedure [dbo].[GetJSON] (
#table_name varchar(max),
#limit int = null,
#ssms bit = 0
)
as
begin
declare #json varchar(max), #query varchar(max), #table_schema varchar(max) = null
if( charindex('.', #table_name) > 0 )
begin
set #table_schema = replace(replace( substring(#table_name, 0, charindex('.',#table_name)), '[', ''), ']', '')
set #table_name = replace(replace( substring(#table_name, charindex('.',#table_name) + 1,len(#table_name)), '[', ''), ']', '')
end
set #query =
'select ' + case when #limit is not null then 'top ' + cast(#limit as varchar(32)) + ' ' else '' end + '''{ '' + REVERSE(STUFF(REVERSE(''' +
CAST((SELECT ' "' + column_name + '" : ' +
case when is_nullable = 'YES'
then ''' + case when [' + column_name + '] is null then ''null'' else ' +
case when data_type like '%char%' or data_type like '%text%' then '''"'' + ' else '' end +
case when data_type like '%date%' then 'convert(varchar(23),[' + column_name + '], 126) + ''Z''' else
'replace(replace(replace(replace(cast([' + column_name + '] as varchar(max)),''\'',''\\''),''"'',''\"''),char(10),''\n''),char(13),''\n'') ' end +
case when data_type like '%char%' or data_type like '%text%' then '+ ''"''' else '' end + ' end + '''
else
case when data_type like '%char%' or data_type like '%text%' then '"' else '' end +
''' + ' +
case when data_type like '%date%' then 'convert(varchar(23),[' + column_name + '], 126) + ''Z' else
'replace(replace(replace(replace(cast([' + column_name + '] as varchar(max)),''\'',''\\''),''"'',''\"''),char(10),''\n''),char(13),''\n'') + ''' end +
case when data_type like '%char%' or data_type like '%text%' then '"' else '' end end + ',' AS [text()]
from information_schema.columns where table_name = #table_name and (#table_schema is null or table_schema = #table_schema) FOR XML PATH('') ) as varchar(max)) +
'''),1,1,'''')) + '' }'' as json into tmpJsonTable from ' + #table_name + ' with(nolock) '
exec sp_sqlexec #query
set #json =
'{' + char(10) + char(9) +
'"recordCount" : ' + Cast((select count(*) from tmpJsonTable) as varchar(32)) + ',' + char(10) + char(9) +
'"records" : ' + char(10) + char(9) + char(9) + '[' + char(10)
+ REVERSE(STUFF(REVERSE(CAST((SELECT char(9) + char(9) + json + ',' + char(10) AS [text()] FROM tmpJsonTable FOR XML PATH('')) AS varchar(max))),1,2,''))
+ char(10) + char(9) + char(9) + ']' + char(10) + '}'
drop table tmpJsonTable
if( #ssms = 1 and len(#json) > 65535 ) --deal with Sql Server Management Studio text/grid truncation
select cast('<json><![CDATA[' + #json + ']]></json>' as xml) as jsonString
else
select #json as jsonString
end
jlech answer is OK, but I don't see why you cannot generate directly off a VIEW's metadata using a technique similar to the one in this UNPIVOT answer, avoiding CURSORs and a SELECT INTO tempoary table.
Not to derail the OP's question, but I am wondering if doing this in SQL is the best / most appropriate route to take? It seems to me that this might be more easily / effectively done in code.
I was initially wondering the same thing (which is how I found this post), but after chewing on the idea for a few minutes, it seems like this might be better accomplished using a utility / extension method that takes a dataset & returns the resulting JSON string.
Granted, the OP may have good reasons for needing to go this route. I'm just thinking (typing) out loud here...