Cannot input parameters in SQL code for MS query - sql-server

I'm creating an Excel report, which other users beside myself could manage.
At the moment I'm struggling with creating the parameters in MS Query, so that they would get the input from a cell in Excel.
Everytime I try to paste my code, where I have changed the original dates with the "question marks" I get the following error.
"Parameters are not allowed in queries that can't be displayed grpahically."
I have tried to create parameters for very simple queries. Like
select *
From dmbase.test
where ID = ?
And there the parameters work, I could add even 10 or more and it would still work.
In addition I have tried to paste the code as it is in SSMS and then later through Data-Properties->Query Properties ->Definitions to change the code and add parameters to the "Command Text" box, but Excel just gives an error.
Also tried to declare variables for my parameters, but that didn't work as well. Gave an error regarding symbols.
declare Parameter1 date(10)
set Parameter1 = ?
declare Parameter2 date(10)
set Parameter2 = ?
I'm not 100% sure that the joins are to blame, but that's my feeling.
My code can be seen below.
select
loc.LocationLang
,loc.DistrictLang
,loc.InventoryRegionLang
,cod.ContractNumber
,cus.CustomerLang
,cus.InternalCustomerType
,cus.CustomerGroupCode
,cus.Organizationalcode
,css.CustomerSubSegmentLang
,loc.AnalysisRegionLang
,dht.ContractHeaderTypeLang
,cod.RentalOutDate
from
dmbase.fContractOpenDetail as cod
left join dmbase.dLocation as loc
on cod.LocationID = loc.LocationID
left join dmbase.dCustomer as cus
on cod.CustomerID = cus.CustomerID
left join dmbase.dCustomerSubSegment as css
on cus.CustomerSubsegmentID = css.CustomerSubSegmentID
left join dmbase.dContractHeaderType as dht
on cod.ContractHeaderTypeAMID = dht.ContractHeaderTypeAMID
where
cod.CompanyID = '6'
and cod.RentalOutDate between ? and ?
and left(loc.LocationLang,4) = '7201'
order by cod.ContractNumber
I would appreciate if you could say, how I could put parameters in so that I would not get the error of "Parameters are not allowed...".

Related

Pass string parameter to SQL over jdbc query in pentaho CDE

I'm trying to pass a string parameter obtained by another query to another query in the same dashboard but when I use the parameter no results was selected. What is the proper syntax or where is the problem.
I'm beginner in pentaho biserver-CE. I use version 6.1. with JDBC connection to SQL Server 2016 SP1.
Now I'm making a sales dashboard from invoices and i want to make a dynamic filter by the time units (which works fine) and by the country shortcuts (which didn't work). If i pass shortcut of some country directly with quotes it works fine but when I replace it by the parameter it doesn't select nothing (Also in CDA preview). When I made some reports in Jasper i used exclamation inside of the parameter to pass quoted value but here I didn't find anything like this for Pentaho.
select top 10
invrow.item as ITEM,
invrow.agent as AGENT,
sum(invrow.qt) as MEASURE,
sum(invrow.val) as VALUE
from invrow
left join invhead on invrow.type = invhead.type
and invrow.nr = invhead.nr
left join art on invrow.item = art.item
where left(invhead.date,4) = ${year}
and invhead.country like ${Country}
group by invrow.item, invrow.agent, invhead.country
order by MEASURE DESC
parameter ${Country} was acquired by another query by the same field. There is a query to gain the parameter:
select distinct
invhead.country
from
invhead
where
left(invhead.date,4) = ${year}
The original query shows nothing but when I Replace parameter ${Country} by for example 'UK' like this.
It works fine:
select top 10
invrow.item as ITEM,
invrow.agent as AGENT,
sum(invrow.qt) as MEASURE,
sum(invrow.val) as VALUE
from invrow
left join invhead on invrow.type = invhead.type
and invrow.nr = invhead.nr
left join art on invrow.item = art.item
where left(invhead.date,4) = ${year}
and invhead.country like 'UK'
group by invrow.item, invrow.agent, invhead.country
order by MEASURE DESC
Now when I use parameter I have nothing in the select list but there are rows, which should be selected.
The syntax is correct, but that way of passing parameters only works for single valued parameters.
To pass an array of parameters, as you seem to be trying, you need to pass the parameter as right hand side of a in operator,
(...)
and invhead.country in ( ${Country} )
(...)
and set the parameter to be of type StringArray.

Replacing a parameter in 2008 R2 SSRS

I am using SSRS 2008 R2 and report builder 3.0. I have a cascading report issue that I need assistance with. The first report runs fine. Clicking on a link in the report passes a #processID parameter to the follow up report.
Now, when running the query with a string instead of the parameter directly in SSMS it takes under 1 second. When I run it through SSRS with the parameter it takes about 15 minutes. I've read that SSRS doesn't handle parameters very well. What I would like to do is find a way to change the parameter into a string and then send that or if anyone knows of a better way.
Below is the query the report is running:
SELECT ResultDetail_View.processOid, ResultDetail_View.applicationId, outputItem.outputValue, ResultDetail_View.startTime, ResultDetail_View.resultStatus,
ResultDetail_View.statusMessage, ResultDetail_View.endTime, ResultDetail_View.ErrRec, COUNT(Summary.Id) AS SumRec
FROM ResultDetail_View LEFT OUTER JOIN
Summary ON ResultDetail_View.processOid = Summary.Id LEFT OUTER JOIN
outputItem ON ResultDetail_View.outputOid = outputItem.outputItemOid
GROUP BY ResultDetail_View.processOid, ResultDetail_View.applicationId, outputItem.outputValue, ResultDetail_View.startTime, ResultDetail_View.resultStatus,
ResultDetail_View.statusMessage, ResultDetail_View.endTime, ResultDetail_View.ErrRec
HAVING (ResultDetail_View.processOid = #processID)
ORDER BY ResultDetail_View.startTime
Regardless of the original issue, it looks like you can change your having to a where without changing the query result? If this is the case that will certainly help with performance.
Regarding the Parameter Sniffing, have you tried setting a local nvarchar variable and running the query this way in the report?
delcare #processIDLocal nvarchar(50) = #processID;
select r.processOid
,r.applicationId
,o.outputValue
,r.startTime
,r.resultStatus
,r.statusMessage
,r.endTime
,r.ErrRec
,count(s.Id) as SumRec
from ResultDetail_View as r
left outer join Summary as s
on r.processOid = s.Id
left outer join outputItem as o
on r.outputOid = o.outputItemOid
where r.processOid = #processID
group by r.processOid
,r.applicationId
,o.outputValue
,r.startTime
,r.resultStatus
,r.statusMessage
,r.endTime
,r.ErrRec
order by r.startTime;

SQL - How can I return a value from a different table base on a parameter?

SQL - How can I return a value from a different table base on a parameter
First time poster, long time reader:
I am using a custom Excel function that allows be to pass parameters and build a SQL string that returns a value. This is working fine. However, I would like to choose among various tables based on the parameters that are passed.
At the moment I have two working functions with SQL statements look like this:
_______FUNCTION ONE________
<SQLText>
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'</SQLText>
_______FUNCTION TWO________
<SQLText>
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'</SQLText>
So I am using IF logic in Excel to check the first parameter and decide which function to use.
It would be much better if I could do a single SQL statement that could pick the right table based on the 1st parameter. Logically something like this:
_______FUNCTIONS COMBINED________
IF '&PARM02' = “A” THEN
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'
ELSE IF '&PARM02' = “B” THEN
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'
ELSE
DESCRIPTION = “”
Based on another post Querying different table based on a parameter I tried this exact syntax with no success
<SQLText>
IF'&PARM02'= "A"
BEGIN
SELECT PRODDTA.F0101.ABALPH as DESCRIPTION
FROM PRODDTA.F0101
WHERE PRODDTA.F0101.ABAN8 = '&PARM02'
END ELSE
BEGIN
SELECT PRODDTA.F4801.WADL01 as DESCRIPTION
FROM PRODDTA.F4801
WHERE PRODDTA.F4801.WADOCO = '&PARM02'
END</SQLText>
You could try using a JOIN statement.
http://www.sqlfiddle.com/#!9/23461d/1
Here is a fiddle showing two tables.
The following code snip will give you the values from both tables, using the Key as the matching logic.
SELECT Table1.description, Table1.key, Table2.description
from Table1
Join Table2 on Table1.key = Table2.key
Here's one way to do it. If PARM03='Use Table1' then the top half of the union will return records and vice versa. This won't necessarily product good performance though. You should consider why you are storing data in this way. It looks like you are partitioning data across different tables which is a bad idea.
SELECT PRODDTA.TABLE1.T1DESC as DESCRIPTION
FROM PRODDTA.TABLE1
WHERE PRODDTA.TABLE1.T1KEY = '&PARM02'
AND &PARM03='Use Table1'
UNION ALL
SELECT PRODDTA.TABLE2.T2DESC as DESCRIPTION
FROM PRODDTA.TABLE2
WHERE PRODDTA.TABLE2.T2KEY = '&PARM02'</SQLText>
AND &PARM03='Use Table2'

SQL Server - Getting XML from result set within one tag

I am trying without much success to build a XML out of my result set.
My result set should look like this :
<CSVRoot>
<CsvColumn>MDCY_Code</CsvColumn>
<CsvColumn>MDCY_Description</CsvColumn>
</CSVRoot>
This is what my query returns :
<CSVRoot>
<CSVHeader>
<CsvColumn>MDCY_Code</CsvColumn>
</CSVHeader>
<CSVHeader>
<CsvColumn>MDCY_Description</CsvColumn>
</CSVHeader>
</CSVRoot>
I know that I can use flowr on this formed XML and remake the XML, but that's additional processing. Is there any way to do this without further processing ( such as using a flowr to form a new XML ) in one query?
This is what I've used:
select
utma.CsvColumn as [ColumnName]
from
Methods m
inner join
UITestMap utm on m.UITestMapID = utm.ID
inner join
SubMethods sm on m.Id = sm.HeaderID
inner join
UITestMapActions utma on sm.UITestMapActionID = utma.ID
for xml path('CSVHeader'),root('CSVRoot')
Edit 2 :
This isn't working, I get the same output.Utma has one column that I need in my query and that is CSVColumn.
Edit 3:
Now I'm getting this :
<CsvHeader>
<ColumnName>MDCY_Cod</ColumnName>
<ColumnName>MDCY_Descriere</ColumnName>
</CsvHeader>
Which is the correct answer.
I wasn't sure how I wanted to process the result sets, actually I will need to use flowr to create a new xml out of this output. ( which is what I needed in the first place)
Try this:
select
utma.CsvColumn
from
Methods m
for xml path(''),root('CSVRoot')

How do I update an XML column in sql server by checking for the value of two nodes including one which needs to do a contains (like) comparison

I have an xml column called OrderXML in an Orders table...
there is an XML XPath like this in the table...
/Order/InternalInformation/InternalOrderBreakout/InternalOrderHeader/InternalOrderDetails/InternalOrderDetail
There InternalOrderDetails contains many InternalOrderDetail nodes like this...
<InternalOrderDetails>
<InternalOrderDetail>
<Item_Number>FBL11REFBK</Item_Number>
<CountOfNumber>10</CountOfNumber>
<PriceLevel>FREE</PriceLevel>
</InternalOrderDetail>
<InternalOrderDetail>
<Item_Number>FCL13COTRGUID</Item_Number>
<CountOfNumber>2</CountOfNumber>
<PriceLevel>NONFREE</PriceLevel>
</InternalOrderDetail>
</InternalOrderDetails>
My end goal is to modify the XML in the OrderXML column IF the Item_Number of the node contains COTRGUID (like '%COTRGUID') AND the PriceLevel=NONFREE. If that condition is met I want to change the PriceLevel column to equal FREE.
I am having trouble with both creating the xpath expression that finds the correct nodes (using OrderXML.value or OrderXML.exist functions) and updating the XML using the OrderXML.modify function).
I have tried the following for the where clause:
WHERE OrderXML.value('(/Order/InternalInformation/InternalOrderBreakout/InternalOrderHeader/InternalOrderDetails/InternalOrderDetail/Item_Number/node())[1]','nvarchar(64)') like '%13COTRGUID'
That does work, but it seems to me that I need to ALSO include my second condition (PriceLevel=NONFREE) in the same where clause and I cannot figure out how to do it. Perhaps I can put in an AND for the second condition like this...
AND OrderXML.value('(/Order/InternalInformation/InternalOrderBreakout/InternalOrderHeader/InternalOrderDetails/InternalOrderDetail/PriceLevel/node())[1]','nvarchar(64)') = 'NONFREE'
but I am afraid it will end up operating like an OR since it is an XML query.
Once I get the WHERE clause right I will update the column using a SET like this:
UPDATE Orders SET orderXml.modify('replace value of (/Order/InternalInformation/InternalOrderBreakout/InternalOrderHeader/InternalOrderDetails/InternalOrderDetail/PriceLevel[1]/text())[1] with "NONFREE"')
However, I ran this statement on some test data and none of the XML columns where updated (even though it said zz rows effected).
I have been at this for several hours to no avail. Help is appreciated. Thanks.
if you don't have more than one node with your condition in each row of Orders table, you can use this:
update orders set
data.modify('
replace value of
(
/Order/InternalInformation/InternalOrderBreakout/
InternalOrderHeader/InternalOrderDetails/
InternalOrderDetail[
Item_Number[contains(., "COTRGUID")] and
PriceLevel="NONFREE"
]/PriceLevel/text()
)[1]
with "FREE"
');
sql fiddle demo
If you could have more than one node in one row, there're a several possible solutions, none of each is really elegant, sadly.
You can reconstruct all xmls in table - sql fiddle demo
or you can do your updates in the loop - sql fiddle demo
This may get you off the hump.
Replace #HolderTable with the name of your table.
SELECT T2.myAlias.query('./../PriceLevel[1]').value('.' , 'varchar(64)') as MyXmlFragmentValue
FROM #HolderTable
CROSS APPLY OrderXML.nodes('/InternalOrderDetails/InternalOrderDetail/Item_Number') as T2(myAlias)
SELECT T2.myAlias.query('.') as MyXmlFragment
FROM #HolderTable
CROSS APPLY OrderXML.nodes('/InternalOrderDetails/InternalOrderDetail/Item_Number') as T2(myAlias)
EDIT:
UPDATE
#HolderTable
SET
OrderXML.modify('replace value of (/InternalOrderDetails/InternalOrderDetail/PriceLevel/text())[1] with "MyNewValue"')
WHERE
OrderXML.value('(/InternalOrderDetails/InternalOrderDetail/PriceLevel)[1]', 'varchar(64)') = 'FREE'
print ##ROWCOUNT
Your issue is the [1] in the above.
Why did I put it there?
Here is a sentence from the URL listed below.
Note that the target being updated must be, at most, one node that is explicitly specified in the path expression by adding a "[1]" at the end of the expression.
http://msdn.microsoft.com/en-us/library/ms190675.aspx
EDIT.
I think I've discovered the the root of your frustration. (No fix, just the problem).
Note below, the second query works.
So I think the [1] is some cases is saying "only ~~search~~ the first node".....and not (as you and I were hoping)...... "use the first node..after you find a match".
UPDATE
#HolderTable
SET
OrderXML.modify('replace value of (/InternalOrderDetails/InternalOrderDetail/PriceLevel/text())[1] with "MyNewValue001"')
WHERE
OrderXML.value('(/InternalOrderDetails/InternalOrderDetail/PriceLevel[text() = "NONFREE"])[1]', 'varchar(64)') = 'NONFREE'
/* and OrderXML.value('(/InternalOrderDetails/InternalOrderDetail/Item_Number)[1]', 'varchar(64)') like '%COTRGUID' */
UPDATE
#HolderTable
SET
OrderXML.modify('replace value of (/InternalOrderDetails/InternalOrderDetail/PriceLevel/text())[1] with "MyNewValue002"')
WHERE
OrderXML.value('(/InternalOrderDetails/InternalOrderDetail/PriceLevel[text() = "FREE"])[1]', 'varchar(64)') = 'FREE'
Try this :
;with InternalOrderDetail as (SELECT id,
Tbl.Col.value('Item_Number[1]', 'varchar(40)') Item_Number,
Tbl.Col.value('CountOfNumber[1]', 'int') CountOfNumber,
case
when Tbl.Col.value('Item_Number[1]', 'varchar(40)') like '%COTRGUID'
and Tbl.Col.value('PriceLevel[1]', 'varchar(40)')='NONFREE'
then 'FREE'
else
Tbl.Col.value('PriceLevel[1]', 'varchar(40)')
end
PriceLevel
FROM (select id ,orderxml from demo)
as a cross apply orderxml.nodes('//InternalOrderDetail')
as
tbl(col) ) ,
cte_data as(SELECT
ID,
'<InternalOrderDetails>'+(SELECT ITEM_NUMBER,COUNTOFNUMBER,PRICELEVEL
FROM InternalOrderDetail
where ID=Results.ID
FOR XML AUTO, ELEMENTS)+'</InternalOrderDetails>' as XML_data
FROM InternalOrderDetail Results
GROUP BY ID)
update demo set orderxml=cast(xml_data as xml)
from demo
inner join cte_data on demo.id=cte_data.id
where cast(orderxml as varchar(2000))!=xml_data;
select * from demo;
SQL Fiddle
I have handled following cases :
1. As required both where clause in question.
2. It will update all <Item_Number> like '%COTRGUID' and <PriceLevel>= NONFREE in one
node, not just the first one.
It may require minor changes for your data and tables.

Resources