I have been on this problem for a couple of days without any Success. Any help would be grateful.
I'm using a dynamic Pivot which works when run in SQL, however when I try to run this query in PHP I get the following error.
Warning:mssql_query() [function.mssql-query]: message: Incorrect
syntax near ','. (severity 15) in XXXXX
I've narrowed it down to how I build the variable in SQL. Although this works in SQL, PHP as a problem with it. I've tested it by defining the variable as SELECT #ColName = '[GEN1.1], [GEN2.2]' which works. I've also tried using a for loop to build the array which didn't work.
SELECT #ColName = ISNULL(#ColName + ', ','') + QUOTENAME(GEN)
Can anyone help with this? Thanks.
An example of my data and SQL query is below.
DECLARE #ColName AS NVARCHAR(MAX);
SELECT #ColName = ISNULL(#ColName + ', ','') + QUOTENAME(GEN)
FROM (SELECT DISTINCT GEN FROM TB) AS Gens
SET #DPQ = N'SELECT STAGE, ' + #ColName + '
INTO #TB2
FROM (see below)
PIVOT (SUM(QTY)
FOR GEN IN (' + #ColName + '))
AS PVTTable
ORDER BY STAGE'
EXEC sp_executesql #DPQ
Table
Stage GEN QTY
A GEN1.1 50
A GEN2.2 125
A GEN2.2 75
C GEN1.1 100
C GEN2.2 25
D GEN1.1 199
D GEN2.2 50
Related
My code:
$sql = "SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '".$data[2]."' OR o = '".$data[4]."' ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
$result = mysql_query($sql) or die(mysql_error());
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'SELECT (#row_number:=#row_number + 1) AS num, player,
reinforcees, reinforcers F' at line 1
When I echo the SQL statement, I get the following: SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '1' OR o = '5' ORDER BY CASE WHEN player = '2' THEN 1 ELSE 2 END
When I run that echod statement through phpMyAdmin, it runs successfully, and gives me rows of results.
But why doesn't it work in a PHP statement? What's going on? How do I get PHP to do what SQL is doing?
And before anyone says I haven't tried to find the answer myself, if you Google "sql variable" php site:stackoverflow.com, every question I find is about accessing SQL results in PHP (i.e., loops) or inserting PHP variables in SQL, which is not what I need. I'm trying to insert an SQL variable into the SQL statement.
Also: I realize I should stop using MySQL, and am in the process of converting, but in order to quickly resolve a bug...I'm using MySQL.
mysql_query doesn't support multiple queries in one call. You would need to upgrade to mysqli or PDO to enable that. In the meantime though, you can implement what you want in a single query using a CROSS JOIN to initialise the row_number variable e.g.
$sql = "SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers
FROM _KoT_villages
CROSS JOIN (SELECT #row_number := 0) r
WHERE o = '".$data[2]."' OR o = '".$data[4]."'
ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
The MySQL client in php expects individual statements
Open MySQL client
First Statement:
SET #row_number = 0
2nd Statement:
SELECT
(#row_number:=#row_number + 1) AS num,
player,
reinforcees,
reinforcers
FROM
_KoT_villages
WHERE
o = '".$data[2]."'
OR o = '".$data[4]."'
ORDER BY
CASE WHEN player = '".$user_class->id."' THEN 1
ELSE 2
END
$result = mysql_query( [2nd Statement] ) or die(mysql_error());
Close MySQL client
Good Day! All Fridays,
I have some problem in my sql query. I'm using IN class with subquery like this
SELECT
cm.category_id,
cd.name
FROM
category_master cm,
category_detail cd,
brand_to_categories b2c
WHERE
cm.category_id = b2c.category_id
AND
cd.category_id = cm.category_id
AND
cd.language_id = 1
AND
cm.status <> 2
AND
cm.category_id IN (SELECT DISTINCT sub_dd.categories FROM distribution_master bdm, distribution_detail bdd, subscription_category_to_brand_user sub_dd WHERE bdd.distribution_id = bdm.distribution_id AND bdm.distributor_id = 35 AND bdd.brand_id = 7191 AND sub_dd.sub_d_id = bdd.id)
AND
b2c.brand_id = 7191;
The following is the sub-query which is creating problem for me.
cm.category_id IN (
SELECT DISTINCT
sub_dd.categories
FROM
distribution_master bdm,
distribution_detail bdd,
subscription_category_to_brand_user sub_dd
WHERE
bdd.distribution_id = bdm.distribution_id
AND
bdm.distributor_id = 35
AND
bdd.brand_id = 7191
AND
sub_dd.sub_d_id = bdd.id)
the result of the sub-query is like this.
3913,4517,6059,7137,7138,7139,7140,7141,7144
this result is coming from only single row in the target table because I stored these ids as string in the filed.
Now the problem is this, I can not get results of the all categories. Main query final result only return one category information which category_id is 3913. But if I run this query manually with sub-query values instead of the sub-query then it returns all the categories results.
Manual query with sub-query values is like this
SELECT
cm.category_id,
cd.name
FROM
category_master cm,
category_detail cd,
brand_to_categories b2c
WHERE
cm.category_id = b2c.category_id
AND
cd.category_id = cm.category_id
AND
cd.language_id = 1
AND
cm.status <> 2
AND
cm.category_id IN (3913,4517,6059,7137,7138,7139,7140,7141,7144)
AND
b2c.brand_id = 7191;
Please help me regarding this problem.
Sorry I forget, I'm using Mysql
Assuming you are using MySQL, use FIND_IN_SET:
WHERE
...
FIND_IN_SET(cm.category_id,
(SELECT DISTINCT sub_dd.categories
FROM distribution_master bdm,
distribution_detail bdd,
subscription_category_to_brand_user sub_dd
WHERE bdd.distribution_id = bdm.distribution_id AND
bdm.distributor_id = 35 AND
bdd.brand_id = 7191 AND
sub_dd.sub_d_id = bdd.id)) > 0
If you are using SQL Server, then we have to do a bit more work:
WHERE ',' + (SELECT DISTINCT ...) + ',' LIKE '%,' + cm.category_id + ',%'
General comment: Avoid storing CSV data in your SQL tables. MySQL almost made the problem worse by offering FIND_IN_SET and making it easier to skirt good table design.
favorite
So I am currently building a system where the user inputs 'interest', 'monthly_deposit' and 'start_date'.
I then want to query the current value of 'FV'.
I need some help writing the query.
I was trying this out, but im getting lost. I think im very wrong, I just need some guidance here
SELECT ((I/C + 1) AND (N*C) + R) * EXP(SUM(COALESCE(LOG)(1)/(I/C)
My values
P = 0 (always)
I = 'interest'
C = 12 (always)
N = 'start_date'
R = 'monthly_deposit'
Try this query
SELECT (P*(POWER((1+(i DIV c)),(n * c)))) + ((R * (POWER((1+(i DIV c)),(n * c)) - 1)) DIV (i DIV c)) as fav
I'm running a connection with PDO to a local MSSQL database. Running any Stored procedure at all through the connection doesn't give me any error at all.
This one single Stored procedure is giving me the following error:
Error in SQL: [Microsoft][SQL Server Native Client 10.0]Invalid cursor state - Query: exec sp_Get_SaldosWeb #Tipo=1, #IdDato=15368
This is my current PDO string for connecting inside this function and returning the array:
$query = $this->db->prepare($qry, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$final = $query->execute();
$this->setRows($query);
if(!$final) {
$this->error($qry, $query, $ret);
} else {
return $query->fetchAll();
}
I've tried closing the cursor both before the execute and after fetchAll like so:
$rows = $query->fetchAll();
$query->closeCursor();
return $rows;
But that also doesn't work. FYI, there are no queries executed before this call to this stored procedure anywhere in my code.
Not sure why this stored procedure is giving so many errors. If I run this exact same SP from MSSQL Management console it runs fine and returns 3 rows.
EDIT:
Here is the stored procedure:
USE [DBNAME]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[sp_Get_SaldosWeb]
#Tipo int , --1 = Alumno 2 = Familia
#IdDato int
as
if #Tipo = 1
begin
select SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos as [Nombre],
SC_Moneda.Nombre as Moneda, upper(replace(replace(replace(replace(replace( replace(lower(SC_TipoCargo.Nombre),char(237),'i'), char(243),'o'), char(233),'e') , char(225),'a') ,char(250),'u'),char(241),'ñ')) as [Tipo de Cargo]
, cast(round(Sum(SC_CargoxAlumno.Debe),2) as decimal(18,2)) as Monto ,
SC_Alumno.Codigo as Codigo2
from SC_CargoxAlumno
inner join SC_Moneda on SC_CargoxAlumno.IdSC_Moneda = SC_Moneda.IdSC_Moneda
inner join SC_TipoCargo on SC_CargoxAlumno.IdSC_TipoCargo = SC_TipoCargo.IdSC_TipoCargo
inner join SC_Alumno on SC_Alumno.IdSC_Alumno = SC_CargoxAlumno.IdSC_Alumno
inner join SC_Familia on SC_Alumno.IdSC_Familia = SC_Familia.IdSC_Familia
where
SC_Alumno.IdSC_Alumno = #IdDato
and SC_CargoxAlumno.Debe <> 0
group by
SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos ,
SC_Moneda.Nombre , SC_TipoCargo.Nombre
end
else
begin
select SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos as [Nombre],
SC_Moneda.Nombre as Moneda, upper(replace(replace(replace(replace(replace( replace(lower(SC_TipoCargo.Nombre),char(237),'i'), char(243),'o'), char(233),'e') , char(225),'a') ,char(250),'u'),char(241),'ñ')) as [Tipo de Cargo] ,
cast(round(Sum(SC_CargoxAlumno.Debe),2) as decimal(18,2)) as Monto ,
SC_Alumno.Codigo as Codigo2
from SC_CargoxAlumno
inner join SC_Moneda on SC_CargoxAlumno.IdSC_Moneda = SC_Moneda.IdSC_Moneda
inner join SC_TipoCargo on SC_CargoxAlumno.IdSC_TipoCargo = SC_TipoCargo.IdSC_TipoCargo
inner join SC_Alumno on SC_Alumno.IdSC_Alumno = SC_CargoxAlumno.IdSC_Alumno
inner join SC_Familia on SC_Alumno.IdSC_Familia = SC_Familia.IdSC_Familia
where
SC_Familia.IdSC_Familia = #IdDato
and SC_CargoxAlumno.Debe <> 0
group by
SC_Alumno.Codigo ,
SC_Alumno.Nombres + ' ' + SC_Alumno.Apellidos ,
SC_Moneda.Nombre , SC_TipoCargo.Nombre
end
Add "SET NOCOUNT ON" to the beginning of your procedure.
You might find references here :
PHP Data Objects
My stored procedure "best practices" checklist
I'm developing using PHP since several years now.
But today I blocked on a problem I cannot explain, it's a very simple concatenation but it's result is bad (missing characters at the end of resulting string);
Here is the code:
$select = $this -> phpSqlCreator -> processSELECT2($this -> phpSqlParser -> parsed);
$from = $this -> phpSqlCreator -> processFROM2($this -> phpSqlParser -> parsed['FROM']);
$where = $this -> whereString;
$sql = $select . ' ' . $from . ' ' . $where;
When I debug this code here is what I see.
The $select variable contains this string :
SELECT DISTINCT t.id as "t.id",t.creation_date as "t.creation_date",t.default_language_code as
"t.default_language_code",t.name as "t.name",t.description as "t.description",t.document_store_path as
"t.document_store_path",t.type as "t.type",t.left_value as "t.left_value",t.right_value as "t.right_value",t.event_id as
"t.event_id",t.parent_id as "t.parent_id",t2.id as "t2.id",t2.creation_date as
"t2.creation_date",t2.default_language_code as "t2.default_language_code",t2.name as "t2.name",t2.description
as "t2.description",t2.document_store_path as "t2.document_store_path",t2.type as "t2.type",t2.left_value as
"t2.left_value",t2.right_value as "t2.right_value",t2.event_id as "t2.event_id",t2.parent_id as "t2.parent_id"
Then, the $from variable contains this string :
FROM team t , (SELECT t.* FROM team t LEFT JOIN team_role tr ON (t.id = tr.team_id) WHERE
tr.participant_id = ? UNION SELECT t.* FROM team t LEFT JOIN team_role tr ON (t.id = tr.team_id) LEFT JOIN
unit_role ur ON (tr.unit_id = ur.unit_id) WHERE ur.participant_id = ?) as dt LEFT JOIN team t2 ON ("t.parent_id" = t2.id)
The $where variable contains :
WHERE t.left_value < dt.left_value and t.right_value > dt.right_value and t.event_id = dt.event_id
The $sql variable contains :
SELECT DISTINCT t.id as "t.id",t.creation_date as "t.creation_date",t.default_language_code as
"t.default_language_code",t.name as "t.name",t.description as "t.description",t.document_store_path as
"t.document_store_path",t.type as "t.type",t.left_value as "t.left_value",t.right_value as "t.right_value",t.event_id as
"t.event_id",t.parent_id as "t.parent_id",t2.id as "t2.id",t2.creation_date as
"t2.creation_date",t2.default_language_code as "t2.default_language_code",t2.name as "t2.name",t2.description
as "t2.description",t2.document_store_path as "t2.document_store_path",t2.type as "t2.type",t2.left_value as
"t2.left_value",t2.right_value as "t2.right_value",t2.event_id as "t2.event_id",t2.parent_id as "t2.parent_id" FROM
team t , (SELECT t.* FROM team t LEFT JOIN team_role tr ON (t.id = tr.team_id) WHERE tr.participant_id = ?
UNION SELECT t.* FROM team t LEFT JOIN team_role tr ON (t.id = tr.team_id) LEFT JOIN unit_role ur ON
(tr.unit_id = ur.unit_id) WHERE ur.participant_id = ?) as dt LEFT JOIN team t2 ON (
The concatenation is very simple but does not work, the end of the $from string variable is missing and the full content of the $where string variable is also missing. I do not understand because the code is very simple.
Furthermore, this peace of code is thorougly executed by a set of automatic unit tests. It's very strange because when the code is executed using PHPUnit (so PHP Cli) the result of the concatenation is good (all our tests are successful).
This concatenation problem is only encountered when the code is executed inside our Web application (standard Apache 2.2.22 + PHP 5.3.13 settings on a Windows 8 machine).
Do you know what could cause this very strange problem? A PHP Setting? An PHP bug with the 5.3.13 version of PHP? Strange characters I do not see in the strings when I'm debugging? Something obvious I didn't see because I'm too tired tonight?
Obviously $sql is operating with a limit of 1024 characters. Either some program is storing something erroneously at the next address, or the $sql variable has a size limitation set somewhere.
From what I can see, in php , a string can be as large as 2GB. There is a memory_limit directive in the php.ini configuration file, but I can't imagine that you have that set to 1024 bytes (1K)
Hi zipzip and thanks for your response.
I finally found that the concatenation was good and that it was my IDE Eclipse which didn't show all the characters into my string.
More info can be found here : http://www.eclipse.org/forums/index.php/m/492856/
So my problem wasn't a problem.
Thanks a lot.
Baptiste