Put a "(" and ")" on string of sqlquery - sql

string sqlquery=
Select userPropID , PropType, PropLoc, PropTranType,PropFloorNo From dbo.tbl_allProperties
WHERE PostPropFor = 'Sale' AND PropCity = '4320-1001041'
AND PropType ='Business Centre' OR PropType ='Space in Shopping Mall' OR PropType ='Commercial Showroom' AND PropImage !='~/user_prop_images/noImage.jpg'
Above sqlquery does not have fix field, it may expand with more fields as user enters value into fields/controls.
My requirement is :
if there is a single 'PropType', do nothing.
if more than one 'PropType', put a '(' before first 'PropType' and
a ')' after the value of last 'PropType'.
Above query should be like this:
Select userPropID , PropType, PropLoc, PropTranType,PropFloorNo From dbo.tbl_allProperties
WHERE PostPropFor = 'Sale' AND PropCity = '4320-1001041'
AND (PropType ='Business Centre' OR PropType ='Space in Shopping Mall' OR PropType ='Commercial Showroom') AND PropImage !='~/user_prop_images/noImage.jpg'

Your description modifies the values on separate rows. If so, you can use row_number() and a case statement:
Select userPropID,
(case when row_number() over (partition by userPropId order by PropTYpe) = 1 then '(' + PropType
when row_number() over (partition by userPropId order by PropTYpe desc) = 1 then PropType + ')'
else PropType
end) as PropType
PropLoc, PropTranType, PropFloorNo
From dbo.tbl_allProperties
where PostPropFor = 'Sale' AND PropCity = '4320-1001041' AND
PropType in ('Business Centre', 'Space in Shopping Mall', 'Commercial Showroom') AND
PropImage !='~/user_prop_images/noImage.jpg';

Related

Error "No column name was specified for column " " of "SOURCE" while select with case on merge

I am trying to select with case on merge in one of my pet projects and I ended up getting error.
I believe this is not the complete query, it is huge in number of lines and I can copy only this from the terminal. I thought maybe someone could help with this code and resolve my issue.
MERGE OrderDetails AS TARGET
USING
(
SELECT OrderHeader.OrderNo, SalesOrderData.[LineNo], SalesOrderData.WebOrderNo, SalesOrderData.quantity,ISNULL(SalesOrderData.BasePrice,'0') AS BasePrice,ISNULL(SalesOrderData.CustomPrice,'0') AS CustomPrice,
ISNULL(SalesOrderData.FinishingPrice,'0')AS FinishingPrice,ISNULL(SalesOrderData.NonDiscount2,'0') AS NonDiscountable, ISNULL(SalesOrderData.TotalPrice,'0') AS TotalPrice,
ISNULL(SalesOrderData.ExtendedPrice,'0') As ExtendedPrice,SalesOrderData.Category,SalesOrderData.StockNo,SalesOrderData.SSD,SalesOrderData.VerticalSS,SalesOrderData.LorH, SalesOrderData.WorB, SalesOrderData.Species,
SalesOrderData.FinishingOption, SalesOrderData.Grade, SalesOrderData.Sheen, SalesOrderData.FinishingBrand,SalesOrderData.ColorName,SalesOrderData.ColorNo,SalesOrderData.StockPaint,
CASE
WHEN SalesOrderData.Category = 'TL' THEN '1.125'
WHEN SalesOrderData.Category = 'RP' THEN '1.125'
WHEN SalesOrderData.Category = 'CTL' THEN '1.25'
WHEN SalesOrderData.Category = 'CTL-BAH' THEN '1.25'
WHEN SalesOrderData.Category = 'CRP' THEN '1.25'
WHEN SalesOrderData.Category = 'IRP' THEN '1.07'
Else SalesOrderData.[SS Thickness]
END
, SalesOrderData.BRD, SalesOrderData.TRD, SalesOrderData.CRD, SalesOrderData.CRD2, SalesOrderData.CRD3, SalesOrderData.CRP1,SalesOrderData.CRP2, SalesOrderData.CRP3, SalesOrderData.Section1, SalesOrderData.Section2,
SalesOrderData.Section3, SalesOrderData.Section4,
CASE
WHEN SalesOrderData.PanelType = 'NA' THEN '-'
Else SalesOrderData.PanelType
END
FROM SalesOrderData
INNER JOIN OrderHeader ON SalesOrderData.WebOrderNo = OrderHeader.WebOrderNo
INNER JOIN OrderDetails ON SalesOrderData.WebOrderNo = OrderDetails.WebOrderNo)
AS SOURCE
ON Source.WebOrderNo = Target.WebOrderNo
WHEN NOT MATCHED BY TARGET
THEN
INSERT
(OrderNo, [LineNo], WebOrderNo, Quantity,BasePrice, CustomPrice, FinishingPrice, NonDiscountable,TotalPrice,ExtendedPrice, Category,StockNo, SSD, VerticalSS,LorH, WorB, Species,FinishingOption, Grade, Sheen,
FinishingBrand, ColorName,ColorNo,StockPaint,SSthick, BRD, TRD, CRD, CRD2, CRD3, CRP1Req,CRP2Req, CRP3Req, Section1, Section2, Section3, Section4,PanelType, RailConfig, ItemText6,SStype, ArchLow, ArchHigh,
LouverDirection, TrimType, TrimLouverDirection,MHLouverDirection, FCRLouverDirection,MHTR,MHCR1,MHCR2,MHCR3,UM,VBoardWidth, VBoardTotal, HBoardWidth,VBoardSpacing,ShutterComments,Custom1,Custom2,Custom3,Custom4,Custom5)
VALUES
(Source.OrderNo,Source.[LineNo], Source.WebOrderNo, Source.Quantity,Source.BasePrice, Source.CustomPrice, Source.FinishingPrice, Source.NonDiscountable,Source.TotalPrice,Source.Source.ExtendedPrice, Source.Category,
Source.StockNo, Source.SSD, Source.VerticalSS,Source.LorH, Source.WorB, Source.Species, Source.FinishingOption, Source.Grade, Source.Sheen, Source.FinishingBrand, Source.ColorName,Source.ColorNo,Source.StockPaint,
Source.SSthick, Source.BRD, Source.TRD, Source.CRD, Source.CRD2, Source.CRD3, Source.CRP1Req,Source.CRP2Req, Source.CRP3Req, Source.Section1, Source.Section2, Source.Section3, Source.Section4,Source.PanelType,
Source.RailConfig, Source.ItemText6,Source.SStype, Source.ArchLow, Source.ArchHigh, Source.LouverDirection, Source.TrimType, Source.TrimLouverDirection,Source.MHLouverDirection, Source.FCRLouverDirection,Source.MHTR,
Source.MHCR1,Source.MHCR2,Source.MHCR3,Source.UM,Source.VBoardWidth, Source.VBoardTotal, Source.HBoardWidth,Source.VBoardSpacing,SSource.hutterComments,Source.Custom1,Source.Custom2,Source.Custom3,Source.Custom4,
Source.Custom5);
Your CASE expressions need aliases. You have, for example:
CASE
WHEN SalesOrderData.Category = 'TL' THEN '1.125'
...
ELSE SalesOrderData.[SS Thickness]
END
,
It needs to be:
SomeMeaningfulAlias = CASE
WHEN SalesOrderData.Category = 'TL' THEN '1.125'
...
ELSE SalesOrderData.[SS Thickness]
END
,
Or:
CASE
WHEN SalesOrderData.Category = 'TL' THEN '1.125'
...
ELSE SalesOrderData.[SS Thickness]
END AS SomeMeaningfulAlias
,

error: syntax error at or near "S" node posgres

My question is I can't resolve the error 42601 which is I know that a syntax error. I run the query on pgadmin and it just works fine. Here's my code
I need to concatenate process of query to solve different requests of user.
ps. im using node posgres promise
return new Promise((resolve,reject)=>{
let {searchType , searchValue , sortType , filterType , size , index} = req.params;
var select_clause = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) `;
var where_clause;
switch(searchType){
case 'MOBILE_NUMBER':
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') `;
break;
case 'SVN_NUMBER':
where_clause = `WHERE (svn_id LIKE '%' || $1 || '%') `;
break;
default: //ALL
where_clause = `WHERE (mobile_number LIKE '%' || $1 || '%') OR (svn_id LIKE '%' || $1 || '%') `;
}
var sort_type;
switch(sortType){
case 'MOBILE_NUMBER':
sort_type = `order by mobile_number `;
break;
case 'SVN_NUMBER':
sort_type = `order by svn_id `;
break;
case 'RENEWAL_DATE':
sort_type = `order by date_subscribed `;
break;
case 'SUBSCRIPTION_DATE':
sort_type = `order by date_created `;
break;
}
var pagination = ` limit $2 offset $3`;
var query = `${select_clause} ${where_clause} ${sort_type} ${filterType} ${pagination}`;
pool.query(query[
searchValue , size , index
],function(err,result){
if(err) {
console.log(err);
reject(err);
}resolve(result);
});
});
response error is:
error: syntax error at or near "S"
at Connection.parseE (/var/www/appvno/admin/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/var/www/appvno/admin/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/var/www/appvno/admin/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at Socket.Readable.push (_stream_readable.js:212:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
length: 89,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '1',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1134',
routine: 'scanner_yyerror'}
I tried just combining them into 1 single query and it just works fine.:
var example_query = `SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
-- total_recycled_svn
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
left join network_prefixes on network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(prefix))
WHERE (mobile_number LIKE '%' || $1 || '%')
order by mobile_number DESC
limit $2 offset $3`;
I researched if its theres a limitation on concatenation of select query but I found nothing. Any help will do, thanks!
EDIT 1: I already checked if spaces are correct and also no missing semicolons... based on 42601 meaning
EDIT 2: Here's my console.log of concatenated query"
SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name , date_created ,
date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE') "total_active_svn",
(select count(*) from svn where status = 'UNASSIGNED') "total_available_svn",
(select count(*) from svn_transactions where (svn_status = 'INACTIVE' OR svn_status = 'INCOMING_SMS_ONLY')) "total_grace_svn"
FROM svn_transactions
LEFT JOIN network_prefixes ON network_prefixes.prefix = substr(svn_transactions.mobile_number,1,length(network_prefixes.prefix)) WHERE (mobile_number LIKE '%' || $1 || '%') order by mobile_number DESC limit $2 offset $3
Still works fine on pgadmin but still error 42601 on node postgres
At this part:
`SELECT svn_id , mobile_number , network_prefixes.prefix , network_prefixes.country_name ,
date_created , date_subscribed , expiry_date , svn_status ,
(select count(*) from svn_transactions where svn_status = 'ACTIVE'
use \ ' instead of ' at 'ACTIVE' (no spaces between \ and ')
Also, why are you using ` to delimit a string? Shouldn't it be ' ?
I found the error. It's not the query but the error was my setup of pool.query. I just forget adding comma after the query and before the values. hehe stupid me
before: pool.query(query[..
after: pool.query(query,[..

Float with Null case condition

In the below code, IN ELSE, what if I don't want to pass 'NOTEQUAL' and pass a NULL Value of Float
select from table as A {
A.objek,
max(case when A.atinn = '0000010530' then fltp_to_dec( A.atflv as abap.dec(5,3) else <what to enter here for null or no values > end ) as DDC
}
group by A.objek
If you need NULL then use NULL
select from table as A {
A.objek,
max(case when A.atinn = '0000010530'
then fltp_to_dec( A.atflv as abap.dec(5,3)
else NULL end ) as DDC
}
group by A.objek
or nothing as suggested by Larnu
select from table as A {
A.objek,
max(case when A.atinn = '0000010530'
then fltp_to_dec( A.atflv as abap.dec(5,3)
end ) as DDC
}
group by A.objek

Sql concatenate result on case

I have a table like this
Nomeutente|data |Controllo
----------|----------|---------
utente1 |11-11-2016|prova1
utente1 |11-11-2016|prova4
utente1 |11-11-2016|prova3
utente2 |11-11-2016|ricontrollo
utente2 |11-11-2016|ricontrollo2
utente2 |11-11-2016|ricontrollo3
utente3 |11-11-2016|ricontrollo3
utente4 |11-11-2016|ricontrollo3
and with case i create a query like a pivot
Select
BASE.data,
Max(Case BASE.Nomeutente When 'utente1' Then base.controllo Else ''
End) As utente1,
Max(Case BASE.Nomeutente When 'utente2' Then base.controllo Else ''
End) As utente2,
Max(Case BASE.Nomeutente When 'utente3' Then base.controllo Else ''
End) As utente3,
Max(Case BASE.Nomeutente When 'utente4' Then base.controllo Else ''
End) As utente4,
From
(Select
Nomeutente,
data,
controllo
From PROVA) As BASE
Group By
base.data
but I want in case that insert all controllo value like
Nomeutente|data |Controllo
----------|----------|---------
utente1 |11-11-2016| prova1,prova4,prova3
utente2 |11-11-2016| ricontrollo,ricontrollo2,ricontrollo3
utente3 |11-11-2016| ricontrollo3
utente4 |11-11-2016| ricontrollo3
what kind of query can I create for make this on postgresql 7.4 ?
First create aggregate (only once):
create aggregate textcat_all(
basetype = text,
sfunc = textcat,
stype = text,
initcond = ''
);
Then you can run:
select
Nomeutente,
"data",
textcat_all(Controllo || ',') as Controllo
from
<table_name>
group by
Nomeutente, "data";
Recommeded reading:
https://www.postgresql.org/docs/7.4/static/sql-createaggregate.html
https://www.postgresql.org/support/versioning/

MVC SQL invalid

I have the following code in my MVC Index function. It is called from a search page that allows the user to search for various string values:
public ViewResult Index(string sortOrder, string YearString,string MonthString,string BudgetTypeString,string DescriptionString)
{
ViewBag.BudgetTypeSortParm = String.IsNullOrEmpty(sortOrder) ? "BudgetType_desc" : "";
ViewBag.MonthSortParm = sortOrder == "Date" ? "Month_desc" : "Month";
ViewBag.YearSortParm = sortOrder == "Date" ? "Year_desc" : "Year"; // 12-24-2014 JR added
ViewBag.DescriptionSortParm = sortOrder == "Description" ? "Description_desc" : "Description";
var budg = from s in db.budgets
select s;
if (!String.IsNullOrEmpty(YearString) ||
!String.IsNullOrEmpty(MonthString) ||
!String.IsNullOrEmpty(BudgetTypeString) ||
!String.IsNullOrEmpty(DescriptionString))
{
budg = budg.Where(s => s.BudgetType.ToUpper().Contains(BudgetTypeString.ToUpper()) ||
String.IsNullOrEmpty(BudgetTypeString) || s.Description.ToUpper().Contains(DescriptionString.ToUpper()) ||
String.IsNullOrEmpty(DescriptionString) ||
s.Month.ToUpper().Contains(MonthString.ToUpper()) ||
String.IsNullOrEmpty(MonthString) ||
s.Year.ToUpper().Contains(YearString.ToUpper()) ||
String.IsNullOrEmpty(YearString));
budg = budg.OrderBy(s => s.BudgetType);
return View(db.budgets.ToList());
}
}
Here is the actual SQL that is converted from the above code:
budg {SELECT
[Extent1].[id] AS [id],
[Extent1].[BudgetType] AS [BudgetType],
[Extent1].[Description] AS [Description],
[Extent1].[Amount] AS [Amount],
[Extent1].[Month] AS [Month],
[Extent1].[Year] AS [Year],
[Extent1].[DateStamp] AS [DateStamp]
FROM [dbo].[budget] AS [Extent1]
WHERE (( CAST(CHARINDEX(UPPER(#p__linq__0),
UPPER([Extent1].[BudgetType])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__1), UPPER([Extent1].[Description])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__2), UPPER([Extent1].[Month])) AS int)) > 0) OR
(( CAST(CHARINDEX(UPPER(#p__linq__3), UPPER([Extent1].[Year])) AS int)) > 0)}
Does anyone know why my strings are incorrectly being converted into integers and how to correct it so the search strings on my search page work correctly?
Let's take a look at just one of the Cast statements:
( CAST(CHARINDEX(UPPER(#p__linq__1), UPPER([Extent1].[Description])) AS int)) > 0)
Take a look at the inner statement. It's actually getting the CharIndex of one string in the other. Basically, does "Description" contain #p__linq__1. CharIndex returns 0 if if the first expression is not found in the other. The result of CharIndex is what is being Cast as int, and then compared to see if it is greater than 0. Which is exactly what you asked it to do when you use .Contains