parameter not passed to a dynamic query in SSRS - reporting-services

I am trying to pass a parameter to a dynamic query but it does not work. The parameter is defined in this report. The following works:
select naz_zloze from Slo_zloze where id_zloze=#zloze
the following does not:
declare #PytanieSQL nvarchar(max);
set #PytanieSQL='select naz_zloze from Slo_zloze where id_zloze=#zloze'
exec sp_executesql #PytanieSQL
In the example below it asks me to declare the scalar variable #zloze.
This is strange as other forum postings indicate this should work.
Any suggestions would be appreciated.
Added:
maybe this will shed some light: after I incidentally opened the query designer from this Dataset's properties window I got a message "The Declare SQL construct or statement is not supported." I'm using Studio 2013

If the datatype of #zlose is numeric then
declare #PytanieSQL nvarchar(max);
set #PytanieSQL='select naz_zloze from Slo_zloze where id_zloze=' + #zloze
exec sp_executesql #PytanieSQL
If #zlose is a string then
declare #PytanieSQL nvarchar(max);
set #PytanieSQL='select naz_zloze from Slo_zloze where id_zloze=''' + #zloze + '''
exec sp_executesql #PytanieSQL

Related

Loop a json object in a SQL Server 2016 stored procudure

I have a JSON api
https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&id=17784783,19505939,217873815946,30166592,30310060,30575739,30837262
I want to send data to a stored procured and because of time I had hired two database programmers.
My question: is the only way to parse a JSON object in SQL Server 2016 is with a cursor? In the past I was parsing the JSON object in a .NET WEB API.
Using
For Each elements As JToken In result
now it's
INSERT INTO #temp_values (value)
SELECT value
FROM OPENJSON (#json, '$.result')
WHERE [key] <> 'uids'
DECLARE #MyCursor CURSOR;
DECLARE #values NVARCHAR(MAX);
BEGIN
SET #MyCursor = CURSOR FOR
SELECT value FROM #temp_values
OPEN #MyCursor
FETCH NEXT FROM #MyCursor INTO #values

How to fix 'JSON text is not properly formatted. Unexpected character '\' is found at position 1.' error in SQL Server

I need to pass a JSON to stored procedure as a string and then convert that sting JSON using OPENJSON. The input parameter need be in string format and it contains \ scape characters.
The open JSON is available in SQL Server 2016, I have tried using OPENJSON without '\', it is perfectly working
This code is working:
DECLARE #test1 NVARCHAR(MAX)='{"name":"john","age":22,"class":"mca"}'
SELECT * FROM OPENJSON(#test1)
This is not working:
DECLARE #test2 NVARCHAR(MAX)='{\"name\":\"john smith\",\"age\":22,\"class\":\"mca\"}'
SELECT * FROM OPENJSON(#test2)
Not the best approach, however:
DECLARE #test2 NVARCHAR(MAX) = '{\"name\":\"john smith\",\"age\":22,\"class\":\"mca\"}';
SELECT j.*
FROM OPENJSON('{"t":"' + #test2 + '"}') t
CROSS APPLY OPENJSON(t.[value]) j
;
Another solution:
SELECT *
FROM OPENJSON(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(#test2,'\\t','\t'),'\\r','\r'),'\\n','\n'),'\\f','\f'),'\\b','\b'),'\"','"'),'\\','\')) t
;

JSON text is not properly formatted. Unexpected character 'N' is found at position 0

I am new to JSON in SQL. I am getting the error "JSON text is not properly formatted. Unexpected character 'N' is found at position 0." while executing the below -
DECLARE #json1 NVARCHAR(4000)
set #json1 = N'{"name":[{"FirstName":"John","LastName":"Doe"}], "age":31, "city":"New York"}'
DECLARE #v NVARCHAR(4000)
set #v = CONCAT('N''',(SELECT value FROM OPENJSON(#json1, '$.name')),'''')
--select #v as 'v'
SELECT JSON_VALUE(#v,'$.FirstName')
the " select #v as 'v' " gives me
N'{"FirstName":"John","LastName":"Doe"}'
But, using it in the last select statement gives me error.
DECLARE #v1 NVARCHAR(4000)
set #v1 = N'{"FirstName":"John","LastName":"Doe"}'
SELECT JSON_VALUE(#v1,'$.FirstName') as 'FirstName'
also works fine.
If you're using SQL Server 2016 or later there is build-in function ISJSON which validates that the string in the column is valid json.
Therefore you can do things like this:
SELECT
Name,
JSON_VALUE(jsonCol, '$.info.address.PostCode') AS PostCode
FROM People
WHERE ISJSON(jsonCol) > 0
You are adding the Ncharacter in your CONCAT statement.
Try changing the line:
set #v = CONCAT('N''',(SELECT value FROM OPENJSON(#json1, '$.name')),'''')
to:
set #v = CONCAT('''',(SELECT value FROM OPENJSON(#json1, '$.name')),'''')
JSON_VALUE function may first be executed on all rows before applying the where clauses. it will depend on execution plan so small things like having top clause or ordering may have a impact on that.
It means that if your json data is invalid anywhere in that column(in the whole table), it will throw an error when the query is executed.
So find and fix those invalid json formats first. for example if that column has a ' instead of " it cannot be parsed and will cause the whole TSQL query to throw an error

unescape diactrics in \u0 format (json) in ms sql (SQL Server)

I'm getting json file, which I load to Azure SQL databese. This json is direct output from API, so there is nothing I can do with it before loading to DB.
In that file, all Polish diactircs are escaped to "C/C++/Java source code" (based on: http://www.fileformat.info/info/unicode/char/0142/index.htm
So for example:
ł is \u0142
I was trying to find some method to convert (unescape) those to proper Polish letters.
In worse case scenario, I can write function which will replace all combinations
Repalce(Replace(Replace(string,'\u0142',N'ł'),'\u0144',N'ń')))
And so on, making one big, terrible function...
I was looking for some ready functions like there is for URLdecode, which was answered here on stack in many topics, and here: https://www.codeproject.com/Articles/1005508/URL-Decode-in-T-SQL
Using this solution would be possible but I cannot figure out cast/convert with proper collation and types in there, to get result I'm looking for.
So if anyone knows/has function that would make conversion in string for unescaping that \u this would be great, but I will manage to write something on my own if I would get right conversion. For example I tried:
select convert(nvarchar(1), convert(varbinary, 0x0142, 1))
I made assumption that changing \u to 0x will be the answer but it gives some Chinese characters. So this is wrong direction...
Edit:
After googling more I found exactly same question here on stack from #Pasetchnik: Json escape unicode in SQL Server
And it looks this would be the best solution that there is in MS SQL.
Onlty thing I needed to change was using NVARCHAR instead of VARCHAR that is in linked solution:
CREATE FUNCTION dbo.Json_Unicode_Decode(#escapedString nVARCHAR(MAX))
RETURNS nVARCHAR(MAX)
AS
BEGIN
DECLARE #pos INT = 0,
#char nvarCHAR,
#escapeLen TINYINT = 2,
#hexDigits TINYINT = 4
SET #pos = CHARINDEX('\u', #escapedString, #pos)
WHILE #pos > 0
BEGIN
SET #char = NCHAR(CONVERT(varbinary(8), '0x' + SUBSTRING(#escapedString, #pos + #escapeLen, #hexDigits), 1))
SET #escapedString = STUFF(#escapedString, #pos, #escapeLen + #hexDigits, #char)
SET #pos = CHARINDEX('\u', #escapedString, #pos)
END
RETURN #escapedString
END
Instead of nested REPLACE you could use:
DECLARE #string NVARCHAR(MAX)= N'\u0142 \u0144\u0142';
SELECT #string = REPLACE(#string,u, ch)
FROM (VALUES ('\u0142',N'ł'),('\u0144', N'ń')) s(u, ch);
SELECT #string;
DBFiddle Demo

The argument 1 of the XML data type method "modify" must be a string literal

Hi i am getting the string literal error when i am trying to add an attribute to the child node. How can i modify my code in order to add an attribute successfully.
declare #count int=(select mxGraphXML.value('count(/mxGraphModel/root/Cell/#Value )','nvarchar') from TABLE_LIST
where Table_ListID=1234 )
declare #index int=1;
while #index<=#count
begin
declare #Value varchar(100)= #graphxml.value('(/mxGraphModel/root/Cell/#Value )[1]','nvarchar');
SET #graphxml.modify('insert attribute copyValueID {sql:variable("#Value ")}
as first into (/mxGraphModel/root/Cell)['+convert(varchar,#index)+']');
end
set #index=#index+1;
end
You're using the addition operator where you should be using the CONCAT function. So
'insert attribute copyValueID {sql:variable("#Value ")}
as first into (/mxGraphModel/root/Cell)['+convert(varchar,#index)+']'
is being coerced into a number. Try:
CONCAT('insert attribute copyValueID {sql:variable("#Value ")}
as first into (/mxGraphModel/root/Cell)[',convert(varchar,#index),']')
instead.
Adam, you can do it in Microsoft T-SQL like this:
declare #sql nvarchar(max)
set #sql = 'set #myxml.modify(''
insert (
attribute scalableFieldId {sql:variable("#sf_id")},
attribute myTypeId {sql:variable("#my_type_id")}
) into (/VB/Condition/Field[#fieldId=sql:variable("#field_id")
and #fieldCode=sql:variable("#field_code")])['+
cast(#instance as varchar(3))+']'')'
exec sp_executesql
#sql
,N'#myxml xml output, #field_code varchar(20),
#field_id varchar(20), #sf_id int, #my_type_id tinyint'
,#myxml = #myxml output
,#field_code = #field_code
,#field_id = #field_id
,#sf_id = #sf_id
,#my_type_id = #my_type_id
See what I've done here? It's just a clever usage of Dynamic SQL to overcome Microsoft's moronic limitation of "string literal error".
IMPORTANT NOTE: yes, you can MOSTLY do this by using sql:variable() in SOME places BUT good luck trying to use it in the node number qualifier inside the square brackets! You can't do this without Dynamic SQL by design!
The trick is not mine actually, I got the idea from https://www.opinionatedgeek.com/Snaplets/Blog/Form/Item/000299/Read after banging my head against the wall for a while.
Feel free to ask questions if my sample does not work or something is not clear.