Multiple string values parameter passing to SP in SSRS - sql-server-2008

I have read and tried most of the related topics on this forum, but most of them don't have a lot of feedback.
So I am using SSRS 2008 R2 with Report Builder 3.
I have a simple SP as follows that filters my data using the IN.
But for some reason its not passing the parameters correctly to my sp and only filter's by the first option I select, hope you can assist.
--SP
#Warehouse varchar(max)
AS
BEGIN
SELECT WBal.Warehouse ,WBal.StockCode,((WBal.[Current] - WBal.Bal1)) CMov,((WBal.Bal1 - WBal.Bal2)) P1Mov,((WBal.Bal2 - WBal.Bal3)) P2Mov
,((WBal.Bal3 - WBal.Bal4)) P3Mov,((WBal.Bal4 - WBal.Bal5)) P4Mov,((WBal.Bal5 - WBal.Bal6)) P5Mov,((WBal.Bal6 - WBal.Bal7)) P6Mov
,((WBal.Bal7 - WBal.Bal8)) P7Mov,((WBal.Bal8 - WBal.Bal9)) P8Mov,((WBal.Bal9 - WBal.Bal10)) P9Mov,((WBal.Bal10 - WBal.Bal11)) P10Mov
,((WBal.Bal11 - WBal.Bal12)) P11Mov
FROM
(
SELECT [StockCode]
,[Warehouse]
,(QtyOnHand * UnitCost) [Current]
,(OpenBalCost1 * OpenBalQty1) Bal1
,(OpenBalCost2 * OpenBalQty2) Bal2
,(OpenBalCost3 * OpenBalQty3) Bal3
,(OpenBalCost4 * OpenBalQty4) Bal4
,(OpenBalCost5 * OpenBalQty5) Bal5
,(OpenBalCost6 * OpenBalQty6) Bal6
,(OpenBalCost7 * OpenBalQty7) Bal7
,(OpenBalCost8 * OpenBalQty8) Bal8
,(OpenBalCost9 * OpenBalQty9) Bal9
,(OpenBalCost10 * OpenBalQty10) Bal10
,(OpenBalCost11 * OpenBalQty11) Bal11
,(OpenBalCost12 * OpenBalQty12) Bal12
FROM [SysproCompanyR].[dbo].[InvWarehouse]
Where Warehouse in (SELECT * FROM dba_parseString_udf((#Warehouse), ' '))
) WBal
END
I have the following udf that apparently will split of the string, but im not that good with this so I don't know if my problem perhaps lies with the udf
UDF
ALTER FUNCTION [dbo].[dba_parseString_udf]
(
#stringToParse VARCHAR(8000)
, #delimiter CHAR(1)
)
RETURNS #parsedString TABLE (stringValue VARCHAR(128))
AS
/*********************************************************************************
Name: dba_parseString_udf
Author: Michelle Ufford, http://sqlfool.com
Purpose: This function parses string input using a variable delimiter.
Notes: Two common delimiter values are space (' ') and comma (',')
Date Initials Description
----------------------------------------------------------------------------
2011-05-20 MFU Initial Release
*********************************************************************************
Usage:
SELECT *
FROM dba_parseString_udf(<string>, <delimiter>);
Test Cases:
1. multiple strings separated by space
SELECT * FROM dbo.dba_parseString_udf(' aaa bbb ccc ', ' ');
2. multiple strings separated by comma
SELECT * FROM dbo.dba_parseString_udf(',aaa,bbb,,,ccc,', ',');
*********************************************************************************/
BEGIN
/* Declare variables */
DECLARE #trimmedString VARCHAR(8000);
/* We need to trim our string input in case the user entered extra spaces */
SET #trimmedString = LTRIM(RTRIM(#stringToParse));
/* Let's create a recursive CTE to break down our string for us */
WITH parseCTE (StartPos, EndPos)
AS
(
SELECT 1 AS StartPos
, CHARINDEX(#delimiter, #trimmedString + #delimiter) AS EndPos
UNION ALL
SELECT EndPos + 1 AS StartPos
, CharIndex(#delimiter, #trimmedString + #delimiter , EndPos + 1) AS EndPos
FROM parseCTE
WHERE CHARINDEX(#delimiter, #trimmedString + #delimiter, EndPos + 1) <> 0
)
/* Let's take the results and stick it in a table */
INSERT INTO #parsedString
SELECT SUBSTRING(#trimmedString, StartPos, EndPos - StartPos)
FROM parseCTE
WHERE LEN(LTRIM(RTRIM(SUBSTRING(#trimmedString, StartPos, EndPos - StartPos)))) > 0
OPTION (MaxRecursion 8000);
RETURN;
END
So what im trying to achieve is, I have a sp that populates my values for my parameter as did the setup like follow in ssrs
SELECT DISTINCT (Warehouse)
FROM [SysproCompanyR].[dbo].[InvWarehouse]
And then in my Dataset for my report where I need to apply this looks I have tried various alternatives in the parameter option:
expression
=JOIN(Parameters!Warehouse.Value,",")

When you pass multiple values from SSRS, it sends the values as comma delimited value1,value2,value3....
In you query you are splitting on white string ' '
Where Warehouse in (SELECT * FROM dba_parseString_udf((#Warehouse), ' '))
It should be using comma , instead of the white space ' '
Where Warehouse in (SELECT * FROM dba_parseString_udf((#Warehouse), ','))

Related

Convert result into doubly nested JSON format

I am trying to convert SQL Server results into a doubly nested JSON format.
Source SQL Server table:
ID
Name
Program
Type
Section
Director
Project
Sr Manager
PCM
Contractor
Cost Client
123
abc
qew
tyu
dd
ghghjg
hkhjk
fghfgf
gnhghj
gghgh
gghhg
456
yui
gdffgf
ghgf
jkjlkll
uiop
rtyuui
rfv
ujmk
rfvtg
efgg
Convert into doubly JSON as shown here:
[
[
{"key":"ID","value":"123"},
{"key":"Name","value":"abc"},
{"key":"Program","value":"qew"},
{"key":"Type","value":"tyu"},
{"key":"Section","value":"dd"},
{"key":"Director","value":"ghghjg"},
{"key":"Project","value":"hkhjk"},
{"key":"Sr Manager","value":"fghfgf"},
{"key":"PCM","value":"gnhghj"},
{"key":"Contractor","value":"gghgh"},
{"key":"Cost Client","value":"gghhg"}
],
[
{"key":"ID","value":"456"},
{"key":"Name","value":"yui"},
{"key":"Program","value":"gdffgf"},
{"key":"Type","value":"ghgfjhjhj"},
{"key":"Section","value":"jkjlkll"},
{"key":"Director","value":"uiop"},
{"key":"Project","value":"rtyuui"},
{"key":"Sr Manager","value":"rfv"},
{"key":"PCM","value":"ujmk"},
{"key":"Contractor","value":"rfvtg"},
{"key":"Cost Client","value":"efgg"}
]
]
Any help would be greatly appreciated.
Edit:
I started with this by rewriting the "FOR JSON AUTO" so that I can add "Key" "Value" text somehow.
But because my table has space in the column name, FOR XML PATH('') giving invalid XML identifier as required by FOR XML error.
that is when I thought of taking community help.
Create PROCEDURE [dbo].[GetSQLtoJSON] #TableName VARCHAR(255)
AS
BEGIN
IF OBJECT_ID(#TableName) IS NULL
BEGIN
SELECT Json = '';
RETURN
END;
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * INTO ##T ' +
'FROM ' + #TableName;
EXECUTE SP_EXECUTESQL #SQL;
DECLARE #X NVARCHAR(MAX) = '[' + (SELECT * FROM ##T FOR XML PATH('')) + ']';
SELECT #X = REPLACE(#X, '<' + Name + '>',
CASE WHEN ROW_NUMBER() OVER(ORDER BY Column_ID) = 1 THEN '{'
ELSE '' END + Name + ':'),
#X = REPLACE(#X, '</' + Name + '>', ','),
#X = REPLACE(#X, ',{', '}, {'),
#X = REPLACE(#X, ',]', '}]')
FROM sys.columns
WHERE [Object_ID] = OBJECT_ID(#TableName)
ORDER BY Column_ID;
DROP TABLE ##T;
SELECT Json = #X;
END
Sample data:
CREATE TABLE [dbo].[Test1](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Col1] [int] NOT NULL,
[Col 2] varchar(50)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Test1] ON
GO
INSERT [dbo].[Test1] ([ID], [Col1], [Col 2]) VALUES (1, 0,'ABCD')
GO
INSERT [dbo].[Test1] ([ID], [Col1] ,[Col 2]) VALUES (2, 1, 'POIU')
GO
SET IDENTITY_INSERT [dbo].[Test1] OFF
GO
You can use the following code:
Inside an APPLY, unpivot the columns as key/value pairs...
... and aggregate using FOR JSON PATH
Use STRING_AGG to do another aggregation.
SELECT '[' + STRING_AGG(CAST(v.json AS nvarchar(max)), ',') + ']'
FROM T
CROSS APPLY (
SELECT *
FROM (VALUES
('ID', CAST(ID AS nvarchar(100))),
('Name', Name),
('Program', Program),
('Type', [Type]),
('Section', Section),
('Director', Director),
('Project', Project),
('Sr Manager', [Sr Manager]),
('PCM', PCM),
('Contractor', Contractor),
('Cost Client', [Cost Client])
) v([key], value)
FOR JSON PATH
) v(json)
db<>fiddle
You cannot use FOR JSON again, because then you will get ["json": [{"key" : ...
first of all check this link you can find what you want
format-query-results-as-json-with-for-json-sql-server
but in your case you can try this
SELECT
ID,Name,Program,Type,Section,
Director,Project,Sr,Manager,PCM,Contractor,Cost,Client
FROM table
FOR JSON AUTO;
check the link there is more sample so it can help you

How can I use FOR JSON to build JSON in this format?

I'd like to use FOR JSON to build a data payload for an HTTP Post call. My Source table can be recreated with this snippet:
drop table if exists #jsonData;
drop table if exists #jsonColumns;
select
'carat' [column]
into #jsonColumns
union
select 'cut' union
select 'color' union
select 'clarity' union
select 'depth' union
select 'table' union
select 'x' union
select 'y' union
select 'z'
select
0.23 carat
,'Ideal' cut
,'E' color
,'SI2' clarity
,61.5 depth
,55.0 [table]
,3.95 x
,3.98 y
,2.43 z
into #jsonData
union
select 0.21,'Premium','E','SI1',59.8,61.0,3.89,3.84,2.31 union
select 0.29,'Premium','I','VS2',62.4,58.0,4.2,4.23,2.63 union
select 0.31,'Good','J','SI2',63.3,58.0,4.34,4.35,2.75
;
The data needs to be formatted as follows:
{
"columns":["carat","cut","color","clarity","depth","table","x","y","z"],
"data":[
[0.23,"Ideal","E","SI2",61.5,55.0,3.95,3.98,2.43],
[0.21,"Premium","E","SI1",59.8,61.0,3.89,3.84,2.31],
[0.23,"Good","E","VS1",56.9,65.0,4.05,4.07,2.31],
[0.29,"Premium","I","VS2",62.4,58.0,4.2,4.23,2.63],
[0.31,"Good","J","SI2",63.3,58.0,4.34,4.35,2.75]
]
}
My attempts thus far is as follows:
select
(select * from #jsonColumns for json path) as [columns],
(select * from #jsonData for json path) as [data]
for json path, without_array_wrapper
However this returns arrays of objects rather than values, like so:
{
"columns":[
{"column":"carat"},
{"column":"clarity"},
{"column":"color"},
{"column":"cut"},
{"column":"depth"},
{"column":"table"},
{"column":"x"},
{"column":"y"},
{"column":"z"}
]...
}
How can I limit the arrays to only showing the values?
Honestly, this seems like it's going to be easier with string aggregation rather than using the JSON functionality.
Because you're using using SQL Server 2016, you don't have access to STRING_AGG or CONCAT_WS, so the code is a lot longer. You have to make use of FOR XML PATH and STUFF instead and insert all the separators manually (why there's so many ',' in the CONCAT expression). This results in the below:
DECLARE #CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SELECT N'{' + #CRLF +
N' "columns":[' + STUFF((SELECT ',' + QUOTENAME(c.[name],'"')
FROM tempdb.sys.columns c
JOIN tempdb.sys.tables t ON c.object_id = t.object_id
WHERE t.[name] LIKE N'#jsonData%' --Like isn't needed if not a temporary table. Use the literal name.
ORDER BY c.column_id ASC
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,1,N'') + N'],' + #CRLF +
N' "data":[' + #CRLF +
STUFF((SELECT N',' + #CRLF +
N' ' + CONCAT('[',JD.carat,',',QUOTENAME(JD.cut,'"'),',',QUOTENAME(JD.color,'"'),',',QUOTENAME(JD.clarity,'"'),',',JD.depth,',',JD.[table],',',JD.x,',',JD.y,',',JD.z,']')
FROM #jsonData JD
ORDER BY JD.carat ASC
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,3,N'') + #CRLF +
N' ]' + #CRLF +
N'}';
DB<>Fiddle

SQL server triming

I am trying to format the licenseenum column in my table by removing everything starting the before space and also I would like to remove any character in licenseenum column starting after '-' including '-'
For example:
current data in Licenseenum GA 350-0
What I'm trying to get 350
Here is my code
select Licenseenum, SUBSTRING (Licenseenum, 4, LEN(Licenseenum)-1)
from licensee
this results
350-0
How would I remove -0 from the results?
Thanks for the help
Try it like this
DECLARE #YourString VARCHAR(100)='GA 350-0';
SELECT SUBSTRING(#YourString,CHARINDEX(' ',#YourString,1),CHARINDEX('-',#YourString,1)-CHARINDEX(' ',#YourString,1));
UPDATE 1
This is quite the same, but better to read
DECLARE #YourString VARCHAR(100)='GA 350-0';
WITH Positions AS
(
SELECT CHARINDEX(' ',#YourString,1) AS posBlank
,CHARINDEX('-',#YourString,1) AS posMinus
)
SELECT SUBSTRING(#YourString,posBlank,posMinus-posBlank)
FROM Positions;
UPDATE 2 Avoid the leading blank...
My logic needs small correction in order to cut the blank before the number:
SELECT SUBSTRING(#YourString,posBlank+1,posMinus-posBlank-1)
Would be the same with the first example...
Please try the below code. Its working fine in SQL Server 2012.
DECLARE #Licenseenum varchar(max)
SET #Licenseenum ='GA 350-0'
DECLARE #TempLicense VARCHAR(100)
DECLARE #License VARCHAR(100)
IF (len(#Licenseenum ) - len(replace(#Licenseenum ,' ',''))>=1)
SET #TempLicense = (SELECT REVERSE(LEFT(REVERSE(#Licenseenum ),CHARINDEX(' ', REVERSE(#Licenseenum ), 1) - 1)))
ELSE
SET #TempLicense = #Licenseenum
SELECT #License = (SELECT LEFT(#TempLicense,LEN(#TempLicense) - charindex('-',reverse(#TempLicense),1)))
SELECT #License AS Licenseenum

Select part of a string between two values SQL 2008

I'm attempting to select a part of a strint between 2 values, i've managed to get it working to about 90% but then get an error -
SUBSTRING(TranText, CHARINDEX('x', TranText) + 1, LEN(TranText) - CHARINDEX('x', TranText) - CHARINDEX('/', REVERSE(TranText)))
The field it is querying is like so
Start Date : 01/02/2013 50 x 156.00/MX + 207.64
with the desired result being
156.00
Now I think the issue is because sometimes the X can have a space before or after it, or no space at all. It gets through about 114,000 rows before throwing
Invalid length parameter passed to the LEFT or SUBSTRING function.
But am struggling to resolve.
The main root cause could be because LEN(#QRY) - CHARINDEX('x', #QRY)-CHARINDEX('/', REVERSE(#QRY)) is less than zero ie, negative value. This in turn will throw error in SUBSTRING since the minimum index for SUBSTRING is zero. Therefore we check that condition in a case statement.
SELECT CASE WHEN LEN(TranText) - CHARINDEX('x',TranText)-CHARINDEX('/', REVERSE(TranText)) >= 0 THEN
SUBSTRING(TranText, CHARINDEX('x', TranText) + 1, LEN(TranText) - CHARINDEX('x', TranText) - CHARINDEX('/', REVERSE(TranText)))
ELSE NULL END
FROM YOURTABLE
Try this. Used REPLACE function and then parsed.
DECLARE #string AS VARCHAR(100), #result AS VARCHAR(100)
DECLARE #nStart AS int
SET #string = 'Start Date : 01/02/2013 50 x 156.00/MX + 207.64'
SET #result = REPLACE(#string, '/', '')
SET #nStart = CHARINDEX('x', #result) + 1
SET #result = SUBSTRING(#result, #nStart, CHARINDEX('M',#result) - #nStart)
SELECT #result

add a counter to a SELECT query's results

I'm trying to add a counter to a list of Select results. Keeping it simple, my query is this:
Select distinct '"'+cast((product_sku) as varchar(30))+'"' as product_sku,preco,'"tamanhoecor::' + Left(Main.preco,Len(Main.preco)-1) + '"' As "custom_price"
From(
Select distinct ST2.product_sku,
(Select cordesc + ' - ' + tamanho +':' + cast(price_dif as varchar) + ';'
From [mg_produtos_preco] ST1
Where ST1.product_sku = ST2.product_sku
ORDER BY ST1.product_sku
For XML PATH ('')) [Preco],
product_price, cordesc,tamanho
From [mg_produtos_preco] ST2) [Main]
Which gets me this:
product_sku preco custom_price
"340803 010" Preto - S:0;Preto - M:0;Preto - L:0;Preto - XL:0; "tamanhoecor::Preto - S:0;Preto - M:0;Preto - L:0;Preto - XL:0"
"340803 100" Branco - S:0;Branco - M:0;Branco - L:0; "tamanhoecor::Branco - S:0;Branco - M:0;Branco - L:0"
However, I need this:
product_sku preco custom_price
"340803 010" Preto - S:0:0;Preto - M:0:1;Preto - L:0:2;Preto - XL:0:3; "tamanhoecor::Preto - S:0:0;Preto - M:0:1;Preto - L:0:2;Preto - XL:0:3"
"340803 100" Branco - S:0:0;Branco - M:0:1;Branco - L:0:2; "tamanhoecor::Branco - S:0:0;Branco - M:0:1;Branco - L:0:2"
I've tried to use what I've found here:
http://msdn.microsoft.com/en-us/library/ms187330%28v=sql.105%29.aspx
I've tried a
DECLARE #pos nvarchar(30)
Select .... (#pos + = 1) ....
from .... (SELECT #pos=0) ....
but I get a "Incorrect syntax near 'DECLARE'. Expecting '(', SELECT, or WITH.", plus a "Incorrect syntax near ="
I tried this code, which worked:
GO
DECLARE #var1 nvarchar(30)
SELECT #var1 = 'Generic Name'
SELECT #var1 = (
SELECT AppUserName
FROM [AppUsers]
WHERE AppUserID = 1000)
SELECT #var1 AS 'Company Name' ;
I would appreciate any help.
Thanks.
what do you mean by counter? Do you want a incremental number per row? If yes, try this:
select row_number() over (order by your_column), *
from your_table